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