Fork me on github

路径总和


思路

递归穷举即可

代码


class Solution {
    public boolean hasPathSum(TreeNode root, int sum) {
        if(root == null){
            return false;
        }
        if(root.left == null && root.right == null){
            return sum - root.val == 0;
        }
        boolean left = false, right = false;
        if(root.left != null){
            left = hasPathSum(root.left, sum - root.val);
        }
        if(root.right != null){
            right = hasPathSum(root.right, sum - root.val);
        }
        return left || right;
    }
}




posted @ 2020-07-07 20:59  zjy4fun  阅读(89)  评论(0编辑  收藏  举报