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 number123
.Find the total sum of all root-to-leaf numbers.
For example,
1 / \ 2 3
The root-to-leaf path
1->2
represents the number12
.
The root-to-leaf path1->3
represents the number13
.Return the sum = 12 + 13 =
25
.
这个题目简单,一次过。DFS就行,我用了个前序遍历,代码:
1 int sumNumbers(TreeNode *root) { 2 if(!root) return 0; 3 int result=0,t=0; 4 preOrder(root,&result,&t); 5 return result; 6 } 7 void preOrder(TreeNode* root,int* sum,int* curSum){ 8 *curSum=*curSum*10+root->val; 9 if(!root->left&&!root->right){//leaf node 10 *sum+=*curSum; 11 return; 12 } 13 if(root->left){ 14 preOrder(root->left,sum,curSum); 15 *curSum/=10; 16 } 17 if(root->right){ 18 preOrder(root->right,sum,curSum); 19 *curSum/=10; 20 } 21 }