LeetCode 之 Path Sum

原题:

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) ;
        }
        
    }

};



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值