Print Binary Tree levels in sorted order
Given a Binary tree, the task is to print its all level in sorted order
Examples:
Input : 7
/ \
6 5
/ \ / \
4 3 2 1
Output :
7
5 6
1 2 3 4
Input : 7
/ \
16 1
/ \
4 13
Output :
7
1 16
4 13
Here we can use two Priority queue for print in sorted order. We create an empty queue q and two priority queues, current_level and next_level. We use NULL as a separator between two levels. Whenever we encounter NULL in normal level order traversal, we swap current_level and next_level.
Level Order traversal of binary tree is
7
5 6
1 2 3 4
No comments:
Post a Comment