LeetCode/solutions/112. Path Sum.md

18 lines
676 B
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [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));
}
};
```