-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathSolution129.java
More file actions
42 lines (35 loc) · 862 Bytes
/
Solution129.java
File metadata and controls
42 lines (35 loc) · 862 Bytes
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
42
package algorithm.leetcode;
/**
* @author: mayuan
* @desc: 求根到叶子节点数字之和
* @date: 2019/03/09
*/
public class Solution129 {
public int sumNumbers(TreeNode root) {
if (null == root) {
return 0;
}
return dfs(root, 0);
}
public int dfs(TreeNode node, int sum) {
if (null == node) {
return 0;
}
int curNumber = sum * 10 + node.val;
// 当前节点为叶子节点
if (null == node.left && null == node.right) {
return curNumber;
} else {
// 非叶子节点
return dfs(node.left, curNumber) + dfs(node.right, curNumber);
}
}
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
}