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.

 

 1 class Solution {
 2 public:
 3     int dfs(TreeNode* root,int sum)
 4     {
 5         if(root==NULL) return  0;
 6         if(root->left==NULL&&root->right==NULL)
 7             return sum*10+root->val;
 8 
 9         return dfs(root->left,sum*10+root->val)+dfs(root->right,sum*10+root->val);
10     }
11     int sumNumbers(TreeNode* root) {
12         return dfs(root,0);
13     }
14 };

 

posted on 2015-05-08 09:52  黄瓜小肥皂  阅读(156)  评论(0编辑  收藏  举报