LeetCode/solutions/112. Path Sum.md

18 lines
676 B
Markdown
Raw Normal View History

2018-11-03 06:25:40 +00:00
# [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));
}
};
```