112 Path Sum

112. Path Sum

1. Question

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.
For example:
Given the below binary tree andsum = 22
1
5
2
/ \
3
4 8
4
/ / \
5
11 13 4
6
/ \ \
7
7 2 1
Copied!
return true, as there exist a root-to-leaf path5->4->11->2which sum is 22.

2. Implementation

(1) Recursion
1
public class Solution {
2
public boolean hasPathSum(TreeNode root, int sum) {
3
if (root == null) return false;
4
5
if(root.left == null && root.right == null) return sum == root.val;
6
7
return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);
8
}
9
}
Copied!
(2) Iteration
1
public boolean hasPathSum(TreeNode root, int sum) {
2
if (root == null) {
3
return false;
4
}
5
6
Stack<TreeNode> nodes = new Stack<>();
7
Stack<Integer> pathSums = new Stack<>();
8
nodes.push(root);
9
pathSums.push(root.val);
10
11
while (!nodes.isEmpty()) {
12
TreeNode curNode = nodes.pop();
13
int curSum = pathSums.pop();
14
15
if (curNode.left == null && curNode.right == null && curSum == sum) {
16
return true;
17
}
18
19
if (curNode.left != null) {
20
nodes.push(curNode.left);
21
pathSums.push(curSum + curNode.left.val);
22
}
23
24
if (curNode.right != null) {
25
nodes.push(curNode.right);
26
pathSums.push(curSum + curNode.right.val);
27
}
28
}
29
return false;
30
}
Copied!

3. Time & Space Complexity

Recursion: 时间复杂度: O(n), 空间复杂度:O(n)
Iteration: 时间复杂度: O(n), 空间复杂度: O(n)