路徑總和
能夠返回true
的情況只有一種可能,就是在葉節點的時候,路徑和剛好爲目標值。
/**
* 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:
int sum;
bool hasPathSum(TreeNode* root, int sum) {
this->sum = sum;
return getSum(root,sum);
}
bool getSum(TreeNode* root,int cnt){
if(!root){
return false;
}
if(!root->left && !root->right){
if(cnt==root->val)
return true;
}
if(root->left){
if(getSum(root->left,cnt-root->val)){
return true;
}
}
if(root->right){
if(getSum(root->right,cnt-root->val)){
return true;
}
}
return false;
}
};