VOOZH about

URL: https://www.geeksforgeeks.org/dsa/print-binary-tree-levels-sorted-order-2/

⇱ Print Binary Tree levels in sorted order | Set 2 (Using set) - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Print Binary Tree levels in sorted order | Set 2 (Using set)

Last Updated : 23 Jan, 2023

Given a tree, print the level order traversal 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

We have discussed a priority queue based solution in below post.
Print Binary Tree levels in sorted order | Set 1 (Using Priority Queue)

In this post, a set (which is implemented using balanced binary search tree) based solution is discussed.

Approach : 

  1. Start level order traversal of tree. 
  2. Store all the nodes in a set(or any other similar data structures). 
  3. Print elements of set.

Implementation:


Output: 
7 5 6 1 2 3 4 

 

Time Complexity: O(n*log(n)) where n is the number of nodes in the binary tree.
Auxiliary Space: O(n) where n is the number of nodes in the binary tree.

Comment