递归
基本思想是从sum中减去当前节点的值,直到它到达叶子节点并且减法等于0,然后我们就知道我们命中了。否则最后的减法不能为 0。
public boolean hasPathSum(TreeNode root, int sum) {
if(root == null) return false;
if(root.left == null && root.right == null && sum - root.val == 0) return true;
return
hasPathSum(root.left, sum - root.val) ||
hasPathSum(root.right, sum - root.val);
}
迭代
public boolean hasPathSum(TreeNode root, int targetSum) {
if(root==null) return false;
Stack<TreeNode> stack = new Stack<TreeNode>();
Stack<Integer> sums = new Stack<Integer>();
stack.push(root);
sums.push(root.val);
while(!stack.isEmpty()&&(root!=null)){
int value = sums.pop();
TreeNode top = stack.pop();
if(top.left==null&&top.right==null&&value==targetSum){
return true;
}else{
if(top.left!=null){
stack.push(top.left);
sums.push(top.left.val+value);
}
if(top.right!=null){
stack.push(top.right);
sums.push(top.right.val+value);
}
}
}
return false;
}