Example:
Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1
bool hasPathSum(struct TreeNode* root, int sum){
if(!root)return false;
if(!root->left&&!root->right){
sum=sum-root->val;
if(sum==0)return true;
return false;
}
if(!root->left){
sum=sum-root->val;
return hasPathSum(root->right,sum);
}
if(!root->right){
sum=sum-root->val;
return hasPathSum(root->left,sum);
}
sum=sum-root->val;
return (hasPathSum(root->right,sum)|hasPathSum(root->left,sum));
}
思路:空樹回傳0,左右子點為空代表只有自己是leaf,看sum扣掉是否為0回傳1,否則表示有子樹。