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 9966120

Browse files
Create Solution 112[CPP]
1 parent 5190758 commit 9966120

File tree

2 files changed

+71
-0
lines changed

2 files changed

+71
-0
lines changed

‎solution/112.Path Sum/README.md‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
## 路径总和
2+
3+
### 问题描述
4+
5+
给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和。
6+
7+
说明: 叶子节点是指没有子节点的节点。
8+
9+
示例:
10+
给定如下二叉树,以及目标和 sum = 22,
11+
```
12+
5
13+
/ \
14+
4 8
15+
/ / \
16+
11 13 4
17+
/ \ \
18+
7 2 1
19+
```
20+
返回 true, 因为存在目标和为 22 的根节点到叶子节点的路径 5->4->11->2。
21+
22+
23+
### 思路
24+
25+
题目要求有没有路径到**叶子节点**使和等于目标值
26+
27+
主要考察对叶子节点是否判断准确
28+
29+
这道题很简单,但是准确率不高,原因是的判断条件不明确,左空右不空返回什么什么,右空左不空返回什么什么,调试一直错
30+
31+
叶子节点唯一判断就是左右空
32+
33+
`root->left == NULL && root->right==NULL`
34+
35+
```CPP
36+
/**
37+
* Definition for a binary tree node.
38+
* struct TreeNode {
39+
* int val;
40+
* TreeNode *left;
41+
* TreeNode *right;
42+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
43+
* };
44+
*/
45+
class Solution {
46+
public:
47+
bool hasPathSum(TreeNode* root, int sum) {
48+
49+
if(root == NULL)return false;
50+
if(root->right == NULL && root->left == NULL && sum == root->val)return true;
51+
52+
bool leftTrue = hasPathSum(root->left,sum - root->val);
53+
bool rightTrue = hasPathSum(root->right,sum - root->val);
54+
55+
return (leftTrue || rightTrue);
56+
}
57+
};
58+
```

‎solution/112.Path Sum/Solution.cpp‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
class Solution {
2+
public:
3+
bool hasPathSum(TreeNode* root, int sum) {
4+
5+
if(root == NULL)return false;
6+
if(root->right == NULL && root->left == NULL && sum == root->val)return true;
7+
8+
bool leftTrue = hasPathSum(root->left,sum - root->val);
9+
bool rightTrue = hasPathSum(root->right,sum - root->val);
10+
11+
return (leftTrue || rightTrue);
12+
}
13+
};

0 commit comments

Comments
(0)

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