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

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

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

public class Solution {
    /**
     * 
     * @param root TreeNode类 
     * @param sum int整型 
     * @return bool布尔型
     */
    boolean flag = false;
    public void dfs(TreeNode root, int sum, int cur) {
        if(root == null)
            return ;
        cur += root.val;
        if(root.left == null && root.right == null){
            if(sum == cur) flag = true;
        }else{
            dfs(root.left, sum, cur);
            dfs(root.right, sum, cur);
        }
    }

    public boolean hasPathSum (TreeNode root, int sum) {
        if(root == null) return false;
        dfs(root, sum ,0);
        return flag;
    }
}
全部评论

相关推荐

AC鸽想进大厂:你是我见过最美的牛客女孩
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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