Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
注意递归的结束条件和题意要求是到叶子结点,非叶子结点不能成立这点就好了
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
return search(root,sum);
}
private boolean search (TreeNode root,int target)
{
if(root==null)return false;
if(root.val==target&&root.left==null&&root.right==null) return true;
return search(root.left,target-root.val)||search(root.right,target-root.val);
}
}