Recursive Solution


  • 0
    M

    // At each node Ni, send it's children value of Si = (S[i-1]10+Ni);
    // When you reach node, add the value to a global sum.
    //Sum is the answer
    class Solution {
    public:
    int sum;
    bool isLeaf(TreeNode
    r)
    {
    if(r->right== NULL && r->left == NULL)
    return true;
    return false;
    }
    void check(TreeNode* t,int s)
    {
    if(isLeaf(t))
    {
    s*=10;
    s+=t->val;
    sum+=s;
    }
    else
    {
    s*=10;
    s+=t->val;
    if(t->left != NULL)
    check(t->left,s);
    if(t->right !=NULL)
    check(t->right,s);
    }
    }
    int sumNumbers(TreeNode* root) {
    if(root== NULL)
    return 0;
    else
    {
    sum =0;
    check(root,0);
    return sum;
    }

    }
    

    };


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.