Wednesday, October 8, 2014

Sum Root to Leaf Numbers

two flavors:

//first one
class Solution {
public:
    int sumNumbers(TreeNode *root) {
        return sumNumbersImpl(root, 0);
    }


    int sumNumbersImpl(TreeNode *root, int num) {
        if (root == nullptr) return 0;
        num = num * 10 + root->val;
        if (root->left == nullptr && root->right == nullptr)
            return num;
        else
            return sumNumbersImpl(root->left, num) + sumNumbersImpl(root->right, num);
    }
};

//second flavor

class Solution {
public:
    int sumNumbers(TreeNode *root) {
        int sum=0,cur=0;
        help(root,sum,cur);
        return sum;
    }
    void help(TreeNode*root,int&sum,int &cur){
        if(!root) return;
        cur=cur*10+root->val;
        if(!root->left&&!root->right)
            sum+=cur;
        help(root->left,sum,cur);
        help(root->right,sum,cur);
        cur/=10;
    }
};

No comments:

Post a Comment