@@ -22,6 +22,7 @@ public class ListOfDepths {
2222 private static List <List <TreeNode >> listOfDepths (TreeNode root ) {
2323 List <List <TreeNode >> listOfDepths = new ArrayList <>();
2424 List <TreeNode > listOfNodesAtCurrentDepth = new ArrayList <>();
25+
2526 if (root != null ) {
2627 listOfNodesAtCurrentDepth .add (root );
2728 }
@@ -31,7 +32,7 @@ private static List<List<TreeNode>> listOfDepths(TreeNode root) {
3132 List <TreeNode > listOfNodesAtPreviousDepth = listOfNodesAtCurrentDepth ; // make current depth as previous
3233 /* make current depth as the new depth to be processed considering
3334 the nodes from the previous depth as parents */
34- listOfNodesAtCurrentDepth = new ArrayList <>();
35+ listOfNodesAtCurrentDepth = new ArrayList <>();
3536
3637 for (TreeNode node : listOfNodesAtPreviousDepth ) {
3738 if (node .left != null ) {
@@ -46,6 +47,42 @@ private static List<List<TreeNode>> listOfDepths(TreeNode root) {
4647 return listOfDepths ;
4748 }
4849
50+ /**
51+ * This is a recursive approach where we pass the depth of each node in the call. We use a
52+ * list {@code listOfDepths} to keep track of all the depths.
53+ *
54+ * @param node
55+ * @param depth
56+ * @param listOfDepths
57+ * @return list of nodes at each depth, where depth starts from 0
58+ */
59+ private static List <List <TreeNode >> listOfDepths (TreeNode node , int depth , List <List <TreeNode >> listOfDepths ) {
60+ if (node == null ) return null ;
61+
62+ List <TreeNode > listOfNodesAtDepth ;
63+ if (depth == listOfDepths .size ()) {
64+ listOfNodesAtDepth = new ArrayList <>();
65+ listOfDepths .add (listOfNodesAtDepth );
66+ } else {
67+ listOfNodesAtDepth = listOfDepths .get (depth );
68+ }
69+
70+ listOfNodesAtDepth .add (node );
71+
72+ listOfDepths (node .left , depth + 1 , listOfDepths );
73+ listOfDepths (node .right , depth + 1 , listOfDepths );
74+
75+ return listOfDepths ;
76+ }
77+
78+ private static void printAllDepths (List <List <TreeNode >> listOfDepths ) {
79+ for (int i = 0 ; i < listOfDepths .size (); i ++) {
80+ System .out .print ("Depth " + i + ": " );
81+ listOfDepths .get (i ).forEach (node -> System .out .print ("->" + node .val ));
82+ System .out .println ();
83+ }
84+ }
85+
4986 public static void main (String [] args ) {
5087 TreeNode treeRoot = new TreeNode (1 );
5188 treeRoot .left = new TreeNode (2 );
@@ -55,11 +92,8 @@ public static void main(String[] args) {
5592 treeRoot .right .left = new TreeNode (6 );
5693 treeRoot .right .right = new TreeNode (7 );
5794
58- List <List <TreeNode >> listOfDepths = listOfDepths (treeRoot );
59- for (int i = 0 ; i < listOfDepths .size (); i ++) {
60- System .out .print ("Depth " + i + ": " );
61- listOfDepths .get (i ).forEach (node -> System .out .print ("->" + node .val ));
62- System .out .println ();
63- }
95+ printAllDepths (listOfDepths (treeRoot ));
96+ System .out .println ("-----" );
97+ printAllDepths (listOfDepths (treeRoot , 0 , new ArrayList <>()));
6498 }
6599}
0 commit comments