forked from MichaelVandi/CodingInterview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path10_25_2020_path_sum.java
More file actions
28 lines (27 loc) · 897 Bytes
/
10_25_2020_path_sum.java
File metadata and controls
28 lines (27 loc) · 897 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
* Time: O(n) or O(2^d) -> where d is the depth of the binary tree
* Space: O(d) -> where d is the depth of the binary tree
*/
class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
if (root == null) {
return false;
}
return hasPathSum(root, sum, 0);
}
public boolean hasPathSum(TreeNode root, int target, int running) {
if (root == null) {
return false;
}
// Add current value to running sum
running += root.val;
// Check if we are at a leaf node
if (root.left == null && root.right == null) {
// return whether this path adds up to target
return running == target;
}
// Go to the left and right paths
return hasPathSum(root.left, target, running) ||
hasPathSum(root.right, target, running);
}
}