路径总和


思路

递归穷举即可

代码


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;
    }
}




原文地址:https://www.cnblogs.com/realzhaijiayu/p/13263166.html