File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments