sum-root-to-leaf-numbers

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

An example is the root-to-leaf path1->2->3which represents the number123.

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

For example,

    1
   / \
  2   3


The root-to-leaf path1->2represents the number12.
The root-to-leaf path1->3represents the number13.

Return the sum = 12 + 13 =25.

/**
 * Definition for binary tree
 * 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) return 0;
        return sumHelp(root,0);
    }
    
    int sumHelp(TreeNode *root,int sum){
        if(!root) return 0;
        if (root->left == nullptr && root->right == nullptr)  
            return sum * 10 + root->val;  
        else 
            return sumHelp(root->left, sum * 10 + root->val)  
            + sumHelp(root->right, sum * 10 + root->val);  
    }
};

 

posted on 2017-03-09 13:33  123_123  阅读(93)  评论(0编辑  收藏  举报