an interseting binary tree questions

题目:
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.
 
 1 class Solution {
 2 public:
 3     int sumNumbers(TreeNode *root) {
 4         int sum = 0;
 5         if(!root) return sum;
 6         return preOrder(root,sum);
 7     }
 8     int preOrder(TreeNode *root, int sum)
 9     {
10         if(!root) return 0;
11          sum = sum*10 + root->val;
12         if(root->left == NULL && root->right == NULL)
13         {
14             return sum;
15         }        
16         return preOrder(root->left,sum)+preOrder(root->right,sum);
17     }
18 };

猜你喜欢

转载自www.cnblogs.com/dzy521/p/9144705.html