Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 9116dde

Browse files
add LeetCode 112. 路径总和
1 parent aa785e3 commit 9116dde

File tree

1 file changed

+91
-0
lines changed

1 file changed

+91
-0
lines changed
Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
![](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9jZG4uanNkZWxpdnIubmV0L2doL2Nob2NvbGF0ZTE5OTkvY2RuL2ltZy8yMDIwMDgyODE0NTUyMS5qcGc?x-oss-process=image/format,png)
2+
>仰望星空的人,不应该被嘲笑
3+
4+
## 题目描述
5+
6+
给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和。
7+
8+
说明: 叶子节点是指没有子节点的节点。
9+
10+
示例:
11+
12+
```javascript
13+
给定如下二叉树,以及目标和 sum = 22,
14+
15+
5
16+
/ \
17+
4 8
18+
/ / \
19+
11 13 4
20+
/ \ \
21+
7 2 1
22+
返回 true, 因为存在目标和为 22 的根节点到叶子节点的路径 5->4->11->2
23+
```
24+
25+
来源:力扣(LeetCode)
26+
链接:https://leetcode-cn.com/problems/path-sum
27+
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
28+
29+
## 解题思路
30+
31+
`dfs`,对于非叶子节点,我们直接减去相应权值,到达了叶子节点,我们判断一下即可,如果满足条件,返回 `true`
32+
33+
```javascript
34+
/**
35+
* Definition for a binary tree node.
36+
* function TreeNode(val) {
37+
* this.val = val;
38+
* this.left = this.right = null;
39+
* }
40+
*/
41+
/**
42+
* @param {TreeNode} root
43+
* @param {number} sum
44+
* @return {boolean}
45+
*/
46+
var hasPathSum = function (root, sum) {
47+
if(!root) return false;
48+
let res = false;
49+
let dfs = (sum, root) => {
50+
// 非叶子节点,就减去权值
51+
sum -= root.val;
52+
// 到达叶子节点,进行判断
53+
if (!root.left && !root.right) {
54+
if (sum === 0) {
55+
res = true;
56+
return;
57+
}
58+
}
59+
// 先遍历左子树,再遍历右子树
60+
root.left && dfs(sum, root.left);
61+
root.right && dfs(sum, root.right);
62+
}
63+
dfs(sum, root);
64+
return res;
65+
};
66+
```
67+
68+
69+
70+
## 最后
71+
文章产出不易,还望各位小伙伴们支持一波!
72+
73+
往期精选:
74+
75+
<a href="https://github.com/Chocolate1999/Front-end-learning-to-organize-notes">小狮子前端の笔记仓库</a>
76+
77+
<a href="https://github.com/Chocolate1999/leetcode-javascript">leetcode-javascript:LeetCode 力扣的 JavaScript 解题仓库,前端刷题路线(思维导图)</a>
78+
79+
小伙伴们可以在Issues中提交自己的解题代码,🤝 欢迎Contributing,可打卡刷题,Give a ⭐️ if this project helped you!
80+
81+
82+
<a href="https://yangchaoyi.vip/">访问超逸の博客</a>,方便小伙伴阅读玩耍~
83+
84+
![](https://img-blog.csdnimg.cn/2020090211491121.png#pic_center)
85+
86+
```javascript
87+
学如逆水行舟,不进则退
88+
```
89+
90+
91+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /