递归:
public boolean hasPathSum(TreeNode root, int sum) {
if(root==null) return false;
if(root.left==null&&root.right==null&&sum==0) return true;
return hasPathSum(root.left, sum-root.val)||hasPathSum(root.right, sum-root.val);
}
迭代:
public boolean hasPathSum(TreeNode root, int sum) {
if (root==null) return false;
Stack<TreeNode> stack=new Stack<TreeNode>();
stack.push(root);
while (!stack.empty()) {
TreeNode t = stack.pop();
if (t.left==null && t.right==null) {
if (t.val == sum) return true;
}
if (t.right!=null) {
t.right.val += t.val;
stack.push(t.right);
}
if (t.left!=null) {
t.left.val += t.val;
stack.push(t.left);
}
}
return false;
}