If we have a binary tree:
7
/ \
5 6
/\ /\
2 3 1 4
/
5
How can I print the below output?
[7],
[5,6]
[2,3,1,4]
[5]
Means doing a BFS and storing nodes at each level in a list and then printing the list?
I am able to traverse in BFS, but I am not able to find correct level of each element in the tree.
How can I find correct level of each node and enrich the node object with its level value?
This is my logic:
Traverse in BFS
Enrich each node of the tree with its level value
Store node in the list
Traverse the list and create a Map of
<Level,List<Node>>
Store the nodes level in a
Set<Integer>
and then convert to list and sort it.Iterate through the newly created List of level and find the appropriate node on that list from map and print it