LeetCode-Path Sum

思路比较简单,只要判断是否为叶子节点,并判断叶子节点的值和传入的 sum 是否相同即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool hasPathSum(TreeNode* root, int sum) {
if(root==nullptr) return false;
if(root->left==nullptr && root->right==nullptr) return sum==root->val;
return hasPathSum(root->left,sum-root->val) || hasPathSum(root->right,sum-root->val);
}
};