Skip to content

Commit 0ce05fb

Browse files
committed
Create 0129-Sum-Root-To-Leaf-Numbers.java
1 parent 94c5381 commit 0ce05fb

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

java/0129-sum-root-to-leaf-numbers.java

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,46 @@
1313
* }
1414
* }
1515
*/
16+
// solution from the video
17+
class Solution {
18+
/*
19+
Time complexity: O(V) where V is the number of vertices
20+
Space complexity: O(h) where h is the height of the tree
21+
*/
22+
23+
public int sumNumbers(TreeNode root) {
24+
// track the sum that we want to add
25+
int solution = 0;
26+
27+
// execute a dfs to find the leaf nodes
28+
solution = findLeafNodes(root, solution);
29+
30+
// return the solution
31+
return solution;
32+
}
33+
34+
// dfs method
35+
public int findLeafNodes(TreeNode node, int currentPath){
36+
// base case, if no node then return 0
37+
if(node==null){
38+
return 0;
39+
}
40+
41+
// add the current node value to the currentPath (move decimal to right by 1 and add)
42+
currentPath = (currentPath * 10) + node.val;
43+
44+
// if we are at a non-null node, check if it is a leaf
45+
if(node.left==null && node.right==null){
46+
// return the solution
47+
return currentPath;
48+
}
49+
50+
// check find the leaf nodes on the left and right
51+
return findLeafNodes(node.left, currentPath) + findLeafNodes(node.right, currentPath);
52+
}
53+
}
54+
55+
// solution using strings
1656
class Solution {
1757
/*
1858
Time complexity: O(V) where V is the number of vertices

0 commit comments

Comments
 (0)