Example:
1
/ \
2 3
/ \ / \
4 5 6 7
==> [1][2, 3][4, 5, 6, 7]
ArrayList
.ArrayList
to store the data of the nodes
and a Queue
to keep track of the nodes
at each level.
ArrayLists
, one for storing the data of all the nodes and the other to store the data of the nodes at each level.Queues
to store nodes at the current level and the next level.root
node to the current level Queue
Queue
becomes empty.Queue
and add its data to the ArrayList that is storing the data of the current level's nodes.Queue
.Current level Queue
becomes empty, add the data of the level Arraylist
to the List
which will be returned.Arraylist
to new List
and add all the nodes from the Next level Queue to the Current level Queue.Loop
i.e. when the current level nodes become empty, return the list
.
public ArrayList<ArrayList<Integer>> printLevelByLevel(TreeNode root) { }
C
Java
Python