Skip to content

Commit b52f6fe

Browse files
committed
add LeetCode 113. 路径总和 II
1 parent d82861b commit b52f6fe

File tree

1 file changed

+118
-0
lines changed

1 file changed

+118
-0
lines changed

Diff for: 二叉树/LeetCode 113. 路径总和 II.md

+118
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
1+
![](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9jZG4uanNkZWxpdnIubmV0L2doL2Nob2NvbGF0ZTE5OTkvY2RuL2ltZy8yMDIwMDgyODE0NTUyMS5qcGc?x-oss-process=image/format,png)
2+
>仰望星空的人,不应该被嘲笑
3+
4+
## 题目描述
5+
给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径。
6+
7+
说明: 叶子节点是指没有子节点的节点。
8+
9+
示例:
10+
11+
```javascript
12+
给定如下二叉树,以及目标和 sum = 22
13+
14+
5
15+
/ \
16+
4 8
17+
/ / \
18+
11 13 4
19+
/ \ / \
20+
7 2 5 1
21+
```
22+
23+
返回:
24+
25+
```javascript
26+
[
27+
[5,4,11,2],
28+
[5,8,4,5]
29+
]
30+
```
31+
32+
来源:力扣(LeetCode)
33+
链接:https://leetcode-cn.com/problems/path-sum-ii
34+
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
35+
36+
## 解题思路
37+
`dfs`,进行深度优先遍历,一直遍历到子节点为止,进行一次判断,如果当前 `sum`为 0 ,那么就是我们想要的结果,然后注意 `js` 语法中形参如果是数组,那么我们拿到的是引用值,可以拷贝一份。
38+
39+
```javascript
40+
/**
41+
* Definition for a binary tree node.
42+
* function TreeNode(val) {
43+
* this.val = val;
44+
* this.left = this.right = null;
45+
* }
46+
*/
47+
/**
48+
* @param {TreeNode} root
49+
* @param {number} sum
50+
* @return {number[][]}
51+
*/
52+
var pathSum = function (root, sum) {
53+
if(!root) return [];
54+
let res = [];
55+
let dfs = (cur, root, sum) => {
56+
if (root == null) return 0;
57+
// 拷贝一份
58+
cur = [...cur,root.val];
59+
sum -= root.val;
60+
if (!root.left && !root.right && sum == 0) {
61+
res.push(cur);
62+
return;
63+
}
64+
// 优先遍历左子树
65+
root.left && dfs(cur, root.left, sum);
66+
root.right && dfs(cur, root.right, sum);
67+
}
68+
dfs([], root, sum);
69+
return res;
70+
};
71+
```
72+
73+
不太明白的小伙伴,这里给一个友好的提示,我们可以打印一下拷贝出来的`cur`,结合图示应该就好理解了,经典的 `dfs`实现的先序遍历。
74+
75+
```javascript
76+
5
77+
/ \
78+
4 8
79+
/ / \
80+
11 13 4
81+
/ \ / \
82+
7 2 5 1
83+
```
84+
85+
```javascript
86+
[ 5 ]
87+
[ 5, 4 ]
88+
[ 5, 4, 11 ]
89+
[ 5, 4, 11, 7 ]
90+
[ 5, 4, 11, 2 ]
91+
[ 5, 8 ]
92+
[ 5, 8, 13 ]
93+
[ 5, 8, 4 ]
94+
[ 5, 8, 4, 5 ]
95+
[ 5, 8, 4, 1 ]
96+
```
97+
98+
## 最后
99+
文章产出不易,还望各位小伙伴们支持一波!
100+
101+
往期精选:
102+
103+
<a href="https://github.com/Chocolate1999/Front-end-learning-to-organize-notes">小狮子前端の笔记仓库</a>
104+
105+
<a href="https://github.com/Chocolate1999/leetcode-javascript">leetcode-javascript:LeetCode 力扣的 JavaScript 解题仓库,前端刷题路线(思维导图)</a>
106+
107+
小伙伴们可以在Issues中提交自己的解题代码,🤝 欢迎Contributing,可打卡刷题,Give a ⭐️ if this project helped you!
108+
109+
110+
<a href="https://yangchaoyi.vip/">访问超逸の博客</a>,方便小伙伴阅读玩耍~
111+
112+
![](https://img-blog.csdnimg.cn/2020090211491121.png#pic_center)
113+
114+
```javascript
115+
学如逆水行舟,不进则退
116+
```
117+
118+

0 commit comments

Comments
 (0)