题目
Given a binary tree and a sum, determine if the tree has a root-to-leaf path
such that adding up all the values along the path equals the given sum.
For example:
Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
思路
思路:判断该节点是否为叶子节点,如果是叶子节点,则判断该节点的val是否与sum相等,如果不是叶子节点,则判断该节点的左右子树中是否存在路径的和等于(sum-root->val);
实现代码如下:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
bool hasPathSum(struct TreeNode* root, int sum) {
//有效性检查
if(root==NULL){
return false;
}
if(root->left==NULL&&root->right==NULL){//到达叶子节点,判断是否等于sum
if(root->val==sum){
return true;
}
else{
return false;
}
}
else{
return hasPathSum(root->left,sum-root->val)||hasPathSum(root->right,sum-root->val);
}
}