N-ary Tree 🌳 Level Order Traversal | BFS | Coding Interview

Ganesh Prasad
4 min readSep 9, 2022

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.

N-ary tree level traversal
N-ary Tree Traversal

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

  1. Create a queue to hold the nodes. Add the root node to the queue.
  2. start a while loop as long as the queue is not empty.
  3. In each loop, run another for loop for the current size of…

--

--

Ganesh Prasad
Ganesh Prasad

Written by Ganesh Prasad

Backend Developer at Appscrip | C++ veteran, 💜 Dart