mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
Create 112. Path Sum.md
This commit is contained in:
parent
dd8fa6310b
commit
22a9600522
17
112. Path Sum.md
Normal file
17
112. Path Sum.md
Normal file
@ -0,0 +1,17 @@
|
||||
# [112. Path Sum](https://leetcode.com/problems/path-sum/description/)
|
||||
# 思路
|
||||
根据题意,若树空则肯定是false,若非空,则:
|
||||
* 若没有左右子树(叶子),判断其值是否满足条件;
|
||||
* 否则,递归判断其左右子树是否满足,只要有一个满足即满足(即或操作)。
|
||||
|
||||
# C++
|
||||
``` C++
|
||||
class Solution {
|
||||
public:
|
||||
bool hasPathSum(TreeNode* root, int sum) {
|
||||
if(root == NULL) return false;
|
||||
if(root -> left == NULL && root -> right == NULL && sum == (root -> val)) return true; // 叶子节点
|
||||
return hasPathSum(root -> left, sum - (root -> val)) || hasPathSum(root -> right, sum - (root -> val));
|
||||
}
|
||||
};
|
||||
```
|
Loading…
Reference in New Issue
Block a user