Skip to content

Commit ac6de7e

Browse files
committed
Added Path Sum - Easy
1 parent 854b62e commit ac6de7e

1 file changed

Lines changed: 28 additions & 0 deletions

File tree

Easy/10_25_2020_path_sum.java

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/**
2+
* Time: O(n) or O(2^d) -> where d is the depth of the binary tree
3+
* Space: O(d) -> where d is the depth of the binary tree
4+
*/
5+
class Solution {
6+
public boolean hasPathSum(TreeNode root, int sum) {
7+
if (root == null) {
8+
return false;
9+
}
10+
return hasPathSum(root, sum, 0);
11+
12+
}
13+
public boolean hasPathSum(TreeNode root, int target, int running) {
14+
if (root == null) {
15+
return false;
16+
}
17+
// Add current value to running sum
18+
running += root.val;
19+
// Check if we are at a leaf node
20+
if (root.left == null && root.right == null) {
21+
// return whether this path adds up to target
22+
return running == target;
23+
}
24+
// Go to the left and right paths
25+
return hasPathSum(root.left, target, running) ||
26+
hasPathSum(root.right, target, running);
27+
}
28+
}

0 commit comments

Comments
 (0)