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

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

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

    public boolean hasPathSum (TreeNode root, int sum) {
        dfs(root, sum);
        return flag;
    }
    public void dfs(TreeNode root, int rest ){    //rest记录剩余值
        if(root == null || flag) return;

        //当叶节点的值与剩余值相等时,true
        if(root.val == rest &&  root.left == null && root.right == null){ 
            flag = true;
            return;
        }
        dfs(root.left , rest - root.val);
        dfs(root.right , rest - root.val);   
    }
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务