File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change 13
13
* }
14
14
* }
15
15
*/
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
16
56
class Solution {
17
57
/*
18
58
Time complexity: O(V) where V is the number of vertices
You can’t perform that action at this time.
0 commit comments