mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
18 lines
676 B
Markdown
18 lines
676 B
Markdown
![]() |
# [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));
|
|||
|
}
|
|||
|
};
|
|||
|
```
|