Skip to content

Commit 0c85e8b

Browse files
committed
112
1 parent 400f0db commit 0c85e8b

File tree

3 files changed

+260
-3
lines changed

3 files changed

+260
-3
lines changed

SUMMARY.md

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,7 @@
102102
* [99. Recover Binary Search Tree](leetcode-99-Recover-Binary-Search-Tree.md)
103103
* [100. Same Tree](leetcode-100-Same-Tree.md)
104104
* [leetcode 100 斩!回顾](leetcode100斩回顾.md)
105-
* [101 题到 111](leetcode-101-200.md)
105+
* [101 题到 112](leetcode-101-200.md)
106106
* [101. Symmetric Tree](leetcode-101-Symmetric-Tree.md)
107107
* [102. Binary Tree Level Order Traversal](leetcode-102-Binary-Tree-Level-Order-Traversal.md)
108108
* [103. Binary Tree Zigzag Level Order Traversal](leetcode-103-Binary-Tree-Zigzag-Level-Order-Traversal.md)
@@ -113,4 +113,5 @@
113113
* [108. Convert Sorted Array to Binary Search Tree](leetcode-108-Convert-Sorted-Array-to-Binary-Search-Tree.md)
114114
* [109. Convert Sorted List to Binary Search Tree](leetcode-109-Convert-Sorted-List-to-Binary-Search-Tree.md)
115115
* [110. Balanced Binary Tree](leetcode-110-Balanced-Binary-Tree.md)
116-
* [111. Minimum Depth of Binary Tree](leetcode-111-Minimum-Depth-of-Binary-Tree.md)
116+
* [111. Minimum Depth of Binary Tree](leetcode-111-Minimum-Depth-of-Binary-Tree.md)
117+
* [112. Path Sum](leetcode-112-Path-Sum.md)

leetcode-101-200.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,4 +18,6 @@
1818

1919
<a href="leetcode-110-Balanced-Binary-Tree.html">110. Balanced Binary Tree</a>
2020

21-
<a href="leetcode-111-Minimum-Depth-of-Binary-Tree.html">111. Minimum Depth of Binary Tree</a>
21+
<a href="leetcode-111-Minimum-Depth-of-Binary-Tree.html">111. Minimum Depth of Binary Tree</a>
22+
23+
<a href="leetcode-112-Path-Sum.html">112. Path Sum</a>

leetcode-112-Path-Sum.md

Lines changed: 254 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,254 @@
1+
# 题目描述(简单难度)
2+
3+
![](https://windliang.oss-cn-beijing.aliyuncs.com/112.jpg)
4+
5+
给定一个`sum`,判断是否有一条从根节点到叶子节点的路径,该路径上所有数字的和等于`sum`
6+
7+
# 解法一 递归
8+
9+
这道题其实和 [111 题](<https://leetcode.wang/leetcode-111-Minimum-Depth-of-Binary-Tree.html>) 是一样的,大家可以先看 [111 题](<https://leetcode.wang/leetcode-111-Minimum-Depth-of-Binary-Tree.html>) 的分析,这道题无非是把 [111 题](<https://leetcode.wang/leetcode-111-Minimum-Depth-of-Binary-Tree.html>) 递归传递的`depth`改为了`sum`的传递。
10+
11+
如果不仔细分析题目,代码可能会写成下边的样子。
12+
13+
```java
14+
public boolean hasPathSum(TreeNode root, int sum) {
15+
if (root == null) {
16+
return false;
17+
}
18+
return hasPathSumHelper(root, sum);
19+
}
20+
21+
private boolean hasPathSumHelper(TreeNode root, int sum) {
22+
if (root == null) {
23+
return sum == 0;
24+
}
25+
return hasPathSumHelper(root.left, sum - root.val) || hasPathSumHelper(root.right, sum - root.val);
26+
}
27+
```
28+
29+
看起来没什么问题,并且对于题目给的样例也是没问题的。但是对于下边的样例:
30+
31+
```java
32+
3
33+
/ \
34+
9 20
35+
/ / \
36+
8 15 7
37+
38+
sum = 12
39+
```
40+
41+
当某个子树只有一个孩子的时候,就会出问题了,可以看 [111 题](<https://leetcode.wang/leetcode-111-Minimum-Depth-of-Binary-Tree.html>) 的分析。
42+
43+
所以代码需要写成下边的样子。
44+
45+
```java
46+
public boolean hasPathSum(TreeNode root, int sum) {
47+
if (root == null) {
48+
return false;
49+
}
50+
return hasPathSumHelper(root, sum);
51+
}
52+
53+
private boolean hasPathSumHelper(TreeNode root, int sum) {
54+
//到达叶子节点
55+
if (root.left == null && root.right == null) {
56+
return root.val == sum;
57+
}
58+
//左孩子为 null
59+
if (root.left == null) {
60+
return hasPathSumHelper(root.right, sum - root.val);
61+
}
62+
//右孩子为 null
63+
if (root.right == null) {
64+
return hasPathSumHelper(root.left, sum - root.val);
65+
}
66+
return hasPathSumHelper(root.left, sum - root.val) || hasPathSumHelper(root.right, sum - root.val);
67+
}
68+
```
69+
70+
# 解法二 BFS
71+
72+
同样的,我们可以利用一个队列对二叉树进行层次遍历。同时还需要一个队列,保存当前从根节点到当前节点已经累加的和。`BFS`的基本框架不用改变,参考 [102 题](<https://leetcode.wang/leetcode-102-Binary-Tree-Level-Order-Traversal.html>)。只需要多一个队列,进行细微的改变即可。
73+
74+
```java
75+
public boolean hasPathSum(TreeNode root, int sum) {
76+
Queue<TreeNode> queue = new LinkedList<TreeNode>();
77+
Queue<Integer> queueSum = new LinkedList<Integer>();
78+
if (root == null)
79+
return false;
80+
queue.offer(root);
81+
queueSum.offer(root.val);
82+
while (!queue.isEmpty()) {
83+
int levelNum = queue.size(); // 当前层元素的个数
84+
for (int i = 0; i < levelNum; i++) {
85+
TreeNode curNode = queue.poll();
86+
int curSum = queueSum.poll();
87+
if (curNode != null) {
88+
//判断叶子节点是否满足了条件
89+
if (curNode.left == null && curNode.right == null && curSum == sum) {
90+
return true;
91+
}
92+
//当前节点和累计的和加入队列
93+
if (curNode.left != null) {
94+
queue.offer(curNode.left);
95+
queueSum.offer(curSum + curNode.left.val);
96+
}
97+
if (curNode.right != null) {
98+
queue.offer(curNode.right);
99+
queueSum.offer(curSum + curNode.right.val);
100+
}
101+
}
102+
}
103+
}
104+
return false;
105+
}
106+
```
107+
108+
# 解法三 DFS
109+
110+
解法一其实本质上就是做了`DFS`,我们知道`DFS`可以用栈去模拟。对于这道题,我们可以像解法二的`BFS`一样,再增加一个栈,去保存从根节点到当前节点累计的和就可以了。
111+
112+
这里的话,用`DFS`里的中序遍历,参考 [94 题](<https://leetcode.wang/leetCode-94-Binary-Tree-Inorder-Traversal.html>)
113+
114+
```java
115+
public boolean hasPathSum(TreeNode root, int sum) {
116+
Stack<TreeNode> stack = new Stack<>();
117+
Stack<Integer> stackSum = new Stack<>();
118+
TreeNode cur = root;
119+
int curSum = 0;
120+
while (cur != null || !stack.isEmpty()) {
121+
// 节点不为空一直压栈
122+
while (cur != null) {
123+
stack.push(cur);
124+
curSum += cur.val;
125+
stackSum.push(curSum);
126+
cur = cur.left; // 考虑左子树
127+
}
128+
// 节点为空,就出栈
129+
cur = stack.pop();
130+
curSum = stackSum.pop();
131+
//判断是否满足条件
132+
if (curSum == sum && cur.left == null && cur.right == null) {
133+
return true;
134+
}
135+
// 考虑右子树
136+
cur = cur.right;
137+
}
138+
return false;
139+
}
140+
```
141+
142+
但是之前讲了,对于这种利用栈完全模拟递归的思路,对时间复杂度和空间复杂度并没有什么提高。只是把递归传递的参数`root``sum`,本该由计算机自动的压栈出栈,由我们手动去压栈出栈了。
143+
144+
所以我们能不能提高一下,比如省去`sum`这个栈?让我们来分析以下。参考 [这里](<https://leetcode.com/problems/path-sum/discuss/36382/Accepted-By-using-postorder-traversal>)
145+
146+
我们如果只用一个变量`curSum`来记录根节点到当前节点累计的和,有节点入栈就加上节点的值,有节点出栈就减去节点的值。
147+
148+
比如对于下边的树,我们进行中序遍历。
149+
150+
```java
151+
3
152+
/ \
153+
9 20
154+
/ \
155+
8 15
156+
157+
curSum = 0
158+
3 入栈, curSum = 33
159+
9 入栈, curSum = 123 -> 9
160+
8 入栈, curSum = 203 -> 9 -> 8
161+
8 出栈, curSum = 123 -> 9
162+
9 出栈, curSum = 3
163+
15 入栈, curSum = 183 -> 9 -> 15
164+
```
165+
166+
此时路径是 `3 -> 9 -> 15`,和应该是 `27`。但我们得到的是 `18`,少加了 `9 `
167+
168+
原因就是我们进行的是中序遍历,当我们还没访问右边的节点的时候,根节点已经出栈了,再访问右边节点的时候,`curSum`就会少一个根节点的值。
169+
170+
所以,我们可以用后序遍历,先访问左子树,再访问右子树,最后访问根节点。再看一下上边的问题。
171+
172+
```java
173+
3
174+
/ \
175+
9 20
176+
/ \
177+
8 15
178+
179+
curSum = 0
180+
3 入栈, curSum = 33
181+
9 入栈, curSum = 123 -> 9
182+
8 入栈, curSum = 203 -> 9 -> 8
183+
8 出栈, curSum = 123 -> 9
184+
15 入栈, curSum = 273 -> 9 -> 15
185+
```
186+
187+
此时路径 `3 -> 9 -> 15` 对应的 `curSum` 就是正确的了。
188+
189+
用栈实现后序遍历,比中序遍历要复杂一些。当访问到根节点的时候,它的右子树可能访问过了,那就把根节点输出。它的右子树可能没访问过,我们需要去遍历它的右子树。所以我们要用一个变量`pre`保存上一次遍历的节点,用来判断当前根节点的右子树是否已经遍历完成。
190+
191+
```java
192+
public List<Integer> postorderTraversal(TreeNode root) {
193+
List<Integer> result = new LinkedList<>();
194+
Stack<TreeNode> toVisit = new Stack<>();
195+
TreeNode cur = root;
196+
TreeNode pre = null;
197+
198+
while (cur != null || !toVisit.isEmpty()) {
199+
while (cur != null) {
200+
toVisit.push(cur); // 添加根节点
201+
cur = cur.left; // 递归添加左节点
202+
}
203+
cur = toVisit.peek(); // 已经访问到最左的节点了
204+
// 在不存在右节点或者右节点已经访问过的情况下,访问根节点
205+
if (cur.right == null || cur.right == pre) {
206+
toVisit.pop();
207+
result.add(cur.val);
208+
pre = cur;
209+
cur = null;
210+
} else {
211+
cur = cur.right; // 右节点还没有访问过就先访问右节点
212+
}
213+
}
214+
return result;
215+
}
216+
```
217+
218+
有了上边的后序遍历,对于这道题,代码就很好改了。
219+
220+
```java
221+
public boolean hasPathSum(TreeNode root, int sum) {
222+
List<Integer> result = new LinkedList<>();
223+
Stack<TreeNode> toVisit = new Stack<>();
224+
TreeNode cur = root;
225+
TreeNode pre = null;
226+
int curSum = 0; //记录当前的累计的和
227+
while (cur != null || !toVisit.isEmpty()) {
228+
while (cur != null) {
229+
toVisit.push(cur); // 添加根节点
230+
curSum += cur.val;
231+
cur = cur.left; // 递归添加左节点
232+
}
233+
cur = toVisit.peek(); // 已经访问到最左的节点了
234+
//判断是否满足条件
235+
if (curSum == sum && cur.left == null && cur.right == null) {
236+
return true;
237+
}
238+
// 在不存在右节点或者右节点已经访问过的情况下,访问根节点
239+
if (cur.right == null || cur.right == pre) {
240+
TreeNode pop = toVisit.pop();
241+
curSum -= pop.val; //减去出栈的值
242+
pre = cur;
243+
cur = null;
244+
} else {
245+
cur = cur.right; // 右节点还没有访问过就先访问右节点
246+
}
247+
}
248+
return false;
249+
}
250+
```
251+
252+
#
253+
254+
这道题还是在考二叉树的遍历,`DFS``BFS`。解法三通过后序遍历节省了`sum`栈,蛮有意思的。

0 commit comments

Comments
 (0)