N-ary Tree 🌳 Level Order Traversal | BFS | Coding Interview
This article explains the BFS approach for this problem. I would say, it is a simple one if you already know how to perform BFS traversal, if you don’t, still you will be fine.
Descrption
Given an N-ary tree, return the level order traversal of its nodes.
An N-ary tree is a tree where each node can have any number of children. After its level order traversal, we have to return its nodes that occur level by level, like the example below.
Solution Using Breadth First Search
Although we can also use DFS to solve this problem, we are going to use iterative BFS for this one. And, for the iterative BFS, we use a queue, why? because we want to process the current level first before moving on to the next level.
Algorithm for the Level Order Traversal
- Create a queue to hold the nodes. Add the root node to the queue.
- start a while loop as long as the queue is not empty.
- In each loop, run another for loop for the current size of…