sundeepblue
4/30/2014 - 4:40 PM

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

sum root to leaf numbers. 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.

void root_to_leaves_path_sum(TreeNode *root, int curr, int &res) {
    if(!root) return;
    curr = 10 * curr + root->val;
    if(root->left == NULL && root->right == NULL) 
        res += curr;
    root_to_leaves_path_sum(root->left, curr, res);
    root_to_leaves_path_sum(root->right, curr, res);
}

int get_sum (TreeNode *r) {
    int res = 0, curr = 0;
    fun(r, curr, res);
    return res;
}