Skip to content

Commit 69033da

Browse files
committed
129.求根节点到叶节点数字之和
1 parent 1c5fd38 commit 69033da

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

leetcode_Java/DoneTitle.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@
5353
122. 买卖股票的最佳时机 II
5454
123. 买卖股票的最佳时机 III
5555
124. 二叉树中的最大路径和
56+
129. 求根节点到叶节点数字之和
5657
130. 被围绕的区域
5758
131. 分割回文串
5859
136. 只出现一次的数字

leetcode_Java/Solution0129.java

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
// 129. 求根节点到叶节点数字之和
2+
3+
4+
/**
5+
* Definition for a binary tree node.
6+
* public class TreeNode {
7+
* int val;
8+
* TreeNode left;
9+
* TreeNode right;
10+
* TreeNode() {}
11+
* TreeNode(int val) { this.val = val; }
12+
* TreeNode(int val, TreeNode left, TreeNode right) {
13+
* this.val = val;
14+
* this.left = left;
15+
* this.right = right;
16+
* }
17+
* }
18+
*/
19+
20+
21+
/*
22+
递归,自顶向下计算:
23+
1、方法功能:入参是节点、前面的数字之和,返回根节点到达当前节点时的数字之和
24+
2、终止条件:节点为空时返回0
25+
3、递归逻辑:根节点到达当前节点时的数字之和 = 前面的数字之和 * 10 + 当前节点值,返回该结果。由于左右节点同样需要计算数字之和,因此调用同样的方法
26+
4、返回结果:节点的左右节点都为空时,返回该节点的数字之和。否则计算左右节点的数字之和,两者相加然后返回。
27+
*/
28+
class Solution {
29+
public int sumNumbers(TreeNode root) {
30+
return dfs(root, 0);
31+
}
32+
33+
private int dfs(TreeNode root, int preSum) {
34+
if (root == null) {
35+
return 0;
36+
}
37+
int sum = preSum * 10 + root.val;
38+
if (root.left == null && root.right == null) {
39+
return sum;
40+
}
41+
return dfs(root.left, sum) + dfs(root.right, sum);
42+
}
43+
44+
}

0 commit comments

Comments
 (0)