Given a binary tree, print level order traversal in a way that nodes of all levels are printed in separate lines.
For example consider the following tree
Example 1: Output for above tree should be 20 8 22 4 12 10 14 Example 2: 1 / \ 2 3 / \ \ 4 5 6 / \ / 7 8 9 Output for above tree should be 1 2 3 4 5 6 7 8 9<
Note that this is different from simple level order traversal where we need to print all nodes together. Here we need to print nodes of different levels in different lines.
The time complexity of the above solution is O(n2)
How to modify the iterative level order traversal (Method 2 of this) to levels line by line?
The idea is similar to this post. We count the nodes at current level. And for every node, we enqueue its children to queue.
1 2 3 4 5 6
Time complexity of this method is O(n) where n is number of nodes in given binary tree.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
- Level order traversal line by line | Set 3 (Using One Queue)
- Level order traversal line by line | Set 2 (Using Two Queues)
- Print a Binary Tree in Vertical Order | Set 3 (Using Level Order Traversal)
- Connect Nodes at same Level (Level Order Traversal)
- Program to delete a line given the line number from a file
- Construct BST from its given level order traversal
- Reverse Level Order Traversal
- Level Order Tree Traversal
- Level order traversal in spiral form
- Zig Zag Level order traversal of a tree using single queue
- Check if two trees are mirror of each other using level order traversal
- Level order traversal with direction change after every two levels
- Level order traversal in spiral form | Using one stack and one queue
- Perfect Binary Tree Specific Level Order Traversal
- Perfect Binary Tree Specific Level Order Traversal | Set 2