It is known that in level order traversal of binary tree with queue, at any time our queue contains all elements of a particular level. So find level with maximum number of nodes in queue.
BFS traversal is an algorithm for traversing or searching tree or graphs . It starts at the tree root , and explores all of the neighbor nodes at the present depth prior to moving on to the nodes at the next depth level.
So at any point the queue of BFS will contain elements of adjacent layers. So this makes the algorithm perfect for this problem.
Algorithm:
- Create the tree, a queue to store the nodes and insert the root in the queue. Create variables level=0,count =0 and level_no=-1
- The implementation will be slightly different, all the elements of same level will be removed in a single iteration.
- Run a loop while size of queue is greater than 0. Get the size of queue (size) and store it. If size is greater than count then update count = size and level_no = level.
- Now run a loop size times, and pop one node from the queue and insert its childrens (if present).
- Increment level.
Level with maximum number of nodes :https://www.geeksforgeeks.org/level-maximum-number-nodes/