Sum_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.
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.

解析

这道题目不难,用递归很好解决,只要有儿子就要加数字,这里的数字组成方式是旧的树*10+新的数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
* Definition for a binary tree node.
* 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;
int sum=0;
getSum(root,root->val,sum);
return sum;

}
void getSum(TreeNode * root,int number,int &sum){
if(root->left)
getSum(root->left,number*10+root->left->val,sum);
if(root->right)
getSum(root->right,number*10+root->right->val,sum);
if(!root->left&&!root->right){
sum += number;
}
}
};

Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×