题解 | #二叉树中和为某一值的路径(一)#

二叉树中和为某一值的路径(一)

http://www.nowcoder.com/practice/508378c0823c423baa723ce448cbfd0c

//本题用深度优先遍历的方法比较简单
//每次到叶子节点时比较一下是否等于sum
/**
 * struct TreeNode {
 *    int val;
 *    struct TreeNode *left;
 *    struct TreeNode *right;
 * };
 */

class Solution {
public:
    /**
     * 
     * @param root TreeNode类 
     * @param sum int整型 
     * @return bool布尔型
     */
    bool hasPathSum(TreeNode* root, int sum) {
        // write code here
        if(root==NULL)//空树直接返回false
            return false;
        int res=0;
       res+=root->val;
        if(root->right==NULL&&root->left==NULL&&res==sum)
            return true;
        bool leftData=hasPathSum(root->left, sum-res);
        bool rightData=hasPathSum(root->right, sum-res);
        if(leftData==true||rightData==true)
            return true;
        else return false;
    }
};
全部评论

相关推荐

群星之怒:不是哥们,你就不好奇瘫痪三十年的老植物人是啥样的吗?
点赞 评论 收藏
分享
评论
3
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务