1
+ /**
2
+ * Definition for a binary tree node.
3
+ * public class TreeNode {
4
+ * int val;
5
+ * TreeNode left;
6
+ * TreeNode right;
7
+ * TreeNode() {}
8
+ * TreeNode(int val) { this.val = val; }
9
+ * TreeNode(int val, TreeNode left, TreeNode right) {
10
+ * this.val = val;
11
+ * this.left = left;
12
+ * this.right = right;
13
+ * }
14
+ * }
15
+ */
16
+ class Solution {
17
+ /*
18
+ Time complexity: O(V) where V is the number of vertices
19
+ Space complexity: O(V) where V is the number of vertices
20
+ */
21
+
22
+ // keep track of the different root to node values as a string
23
+ List <String > rootToLeafs = new ArrayList <String >();
24
+
25
+ public int sumNumbers (TreeNode root ) {
26
+ // track the sum that we want to add
27
+ int solution = 0 ;
28
+
29
+ String currentPath = "" ;
30
+
31
+ // execute a dfs to find the leaf nodes
32
+ findLeafNodes (root , currentPath );
33
+
34
+ // loop through all the paths, convert to int, add to solution
35
+ for (String curr :rootToLeafs ){
36
+ // save the current string as an integer
37
+ int currentVal = Integer .parseInt (curr );
38
+
39
+ // add the current value to the solution
40
+ solution +=currentVal ;
41
+ }
42
+
43
+ // return the solution
44
+ return solution ;
45
+ }
46
+
47
+ // dfs method
48
+ public void findLeafNodes (TreeNode node , String currentPath ){
49
+ // base case, if no node then return
50
+ if (node ==null ){
51
+ return ;
52
+ }
53
+
54
+ // add the current node value to the currentPath string
55
+ currentPath +=Integer .toString (node .val );
56
+
57
+ // check the left most value
58
+ findLeafNodes (node .left , currentPath );
59
+
60
+ // check the right most value
61
+ findLeafNodes (node .right , currentPath );
62
+
63
+ // if we are at a non-null node, check if it is a leaf
64
+ if (node .left ==null && node .right ==null ){
65
+ // add the currentPath to the arraylist
66
+ rootToLeafs .add (currentPath );
67
+ }
68
+ }
69
+ }
0 commit comments