[Algorithm] Level Order Binary Tree Traversal (Iterative and Recursive)

Traverse a binary tree in level order is intuitive. We can initialize a queue and add elements. Every cycle you need to print out the nodes in the queue, and add their children to queue, until queue is empty.

However, since the recursive solution for pre-order, in-order, and post-order traverse is quite easy, I wonder if level traverse is also simple. I think about it and finally had a solution. Though it’s simple, it’s different from the traverse mentioned above.

In this code I test a simple tree. To use the function, you need to know the height of the tree. It’s very easy to know using recursion.

In the for cycle, we print out data of nodes of each level. The recursive function is simple. It outputs data only when level=1. Otherwise it will try to output its next level.