leetcode解题: Sum Root to Leaf Numbers (129)

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.

Hide Tags Tree Depth-first Search
Show Similar Problems

解法1: DFS , O(N) Space + O(N) Time

题意是对每一个path做一个操作(记录成一个数字),容易想到用DFS来遍历整棵数。
遍历的时候用一个vector存储每一个数字,最后对vector求一下和。
C++

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
29
30
31
32
33
34
35
36
37
38
39
40
41
/**
* 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;
}
vector<int> temp;
helper(root, temp, 0);
int sum = 0;
for (int i = 0; i < temp.size(); ++i) {
sum += temp[i];
}
return sum;
}
void helper(TreeNode* root, vector<int>& buf, int cur) {
if (!root) {
return;
}
cur = cur * 10 + root->val;
if (!root->left && !root->right) {
buf.push_back(cur);
return;
}
helper(root->left, buf, cur);
helper(root->right, buf, cur);
}
};

Java

1

解法2: DFS , O(1) Space + O(N) Time

实际上不需要用一个vector来存储见到的数字。
C++

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
29
30
31
32
33
34
35
36
/**
* 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;
}
return helper(root, 0);
}
int helper(TreeNode* root, int cur) {
if (!root) {
return 0;
}
cur = cur * 10 + root->val;
if (!root->left && !root->right) {
return cur;
}
int sum = helper(root->left, cur) + helper(root->right, cur);
return sum;
}
};