In this tutorial, we will see the Level Order Traversal of a Binary Tree. This traversal is also known as BFS (breadth-first-search)traversal of a tree, because it visits the node from top of the tree and then goes down level by level. Now, let us have a look on a pictorial representation of Level Order Traversal.
The output of above shown tree would be: 2 5 10 20 30
Approach:
- Firstly, we will find the height of the tree so that we can know how many levels are there to traverse.
- Then we will start a loop from i to height of tree.
- Then we will call a method levelOrder() which will print nodes level by level.
Algorithm for levelOrder()method:
public void levelOrder(Node node, int level, List<Integer> ls) {
if (node == null) return;
if (level == 0) add node.val into ls
else {
call levelOrder(node.left, level - 1, ls);
call levelOrder(node.right, level - 1, ls);
}
}
Code Implementation:
Output:
[[2], [5, 10], [20, 30]]
Complexity Analysis:
Time Complexity: O(n2), In skewed tree the time worst case time complexity of recursive approach can go upto O(n2).
Space Complexity: In case of Skewed Tree O(n) and O(log n) if given tree is complete Binary Tree.