题解 | #二叉树中是否存在节点和为指定值的路径#

二叉树中是否存在节点和为指定值的路径

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

递归

/**
 * 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
        target = sum;
        helper(root, 0);
        return isExist;
    }
    bool isExist = false;
    int target;
    void helper(TreeNode* root, int sum){
        if(root == NULL) return;
        //if(sum > target) return;  节点值未必是正数!
        sum += root -> val;
        if(root -> left == NULL && root -> right == NULL){
            if(sum == target) isExist = true;
        }else{
            if(!isExist) helper(root -> left, sum);
            if(!isExist) helper(root -> right, sum);
        }
    }
};
全部评论

相关推荐

ALEX_BLX:这华子能怪谁呢,池子泡这么深,每年几乎都是最晚一批开出来的公司,人才早就给抢走了。又不是人人都是博士生
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务