112. Path Sum

1.递归搜索树

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    boolean visit(TreeNode root,int want,int now){
        if(root == null) return false;
        if(root.left == null  root.right == null) //left
            return (now + root.val) == want;
        return (visit(root.left,want,now + root.val) || visit(root.right,want,now + root.val));
    }
    public boolean hasPathSum(TreeNode root, int sum) {
        if(root == null) {
            return false;
        }
        return visit(root,sum,0);
            
        
    }
}


最新回复(0)
/jishu2WCVloOJxWpuMXeWer4ncs7Ew79AY5U7KvLOLVJMqC4_3D4834083
8 简首页