Sum Root to Leaf Numbers @LeetCode

PROBLEM :

Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.

An example is the root-to-leaf path 1->2->3 which represents the number 123.

Find the total sum of all root-to-leaf numbers.

For example,

    1
   / \
  2   3
The root-to-leaf path 1->2 represents the number 12.
The root-to-leaf path 1->3 represents the number 13.

Return the sum = 12 + 13 = 25.
   
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

class Solution {
public:
    int sumNumbers(TreeNode* root) {
        if(root==NULL)
            return 0 ;
           
        if(root->left==NULL&&root->right==NULL)
            return root->val ;
           
        return SumNumPath(root->left,root->val)+ SumNumPath(root->right,root->val) ;
    }
   
    int  SumNumPath(TreeNode *root,int ele){
        if(root==NULL)
            return 0 ;
        if(root->left==NULL&&root->right==NULL)
            return ele*10+root->val ;
       
        int l,r ;
        l=0,r=0 ;
       
        if(root->left)
            l= SumNumPath(root->left,ele*10+root->val) ;
        if(root->right)
            r= SumNumPath(root->right,ele*10+root->val) ;
           
        return l+r ;
    }
};

---------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )