原题:
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
,
二叉树的题目,用递归非常简单,只要能把递归式写出来就ok,这里我用的递归式是:
hasPathSum(root->left , sum-root->val)||hasPathSum(root->right,sum-root->val);
即只要左子树或右子树有一个符合条件就返回true
这里有一个困扰,开始认为root为null时,sum为0,是真。。。没想到root为NULL要返回false。。。。。无语了,要不两行代码就搞定了。。不过这个代码就是整个算法的精髓,
两行代码如下:
bool hasPathSum(TreeNode *root, int sum) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if(root==NULL) return (0==sum);
else return hasPathSum(root->left , sum-root->val)||hasPathSum(root->right,sum-root->val);
}
学渣就是学渣,不让这么搞,就得分别判断,尤其是利用递归时,要把返回情况仔细考虑,我这里分四种:
1 左右都不为空,返回左右子树的bool值的并值
2 都为空,返回判断该节点的val与sum的相等判断
3 左不为空,返回左子树的bool值
4 右不为空,返回右子树的bool值
这里需要注意的是,这里的值不是节点数,而是每个节点的val的值的和,因此减的时候要注意
代码如下:60 ms
class Solution {
public:
bool hasPathSum(TreeNode *root, int sum) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
//if(root==NULL) return (0==sum);
//else return hasPathSum(root->left , sum-1)||hasPathSum(root->right,sum-1);
if(root==NULL) return false;
if(root->left != NULL && root->right != NULL){
//左右子树都不为空,返回左右子树的并。。。这里注意减去的不是1,是root->val
return hasPathSum(root->left , sum-root->val)||hasPathSum(root->right,sum-root->val);
}
else if(root->left == NULL && root->right == NULL ){
//左右子树都为空,返回root->val 与 sum的判定值
return (root->val==sum);
}
else if(root->left != NULL){
//左子树不为空,返回root->left 与 sum的判定值
return hasPathSum(root->left,sum-root->val) ;
}
else {
//右子树不为空,返回root->right 与 sum的判定值
return hasPathSum(root->right,sum-root->val) ;
}
}
};