Given a tree, print the level order traversal in sorted order.
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.
In this post, a set (which is implemented using balanced binary search tree) based solution is discussed.
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.
# Python3 program to pr level order
# traversal in sorted order
# Helper function that allocates a new
# node with the given data and None
# left and right poers.
# Construct to create a new node
def __init__(self, key):
self.data = key
self.left = None
self.right = None
# Function to pr sorted
# level order traversal
def sorted_level_order( root):
q = 
s = set()
tmp = q
if (tmp == None):
if (not len(s)):
for i in s:
print(i, end = ” “)
s = set()
if (tmp.left != None):
if (tmp.right != None):
# Driver Code
if __name__ == ‘__main__’:
Let us create Binary Tree shown
in above example “””
root = newNode(7)
root.left = newNode(6)
root.right = newNode(5)
root.left.left = newNode(4)
root.left.right = newNode(3)
root.right.left = newNode(2)
root.right.right = newNode(1)
# This code is contributed by
# Shubham Singh(SHUBHAMSINGH10)
7 5 6 1 2 3 4
- Print Binary Tree levels in sorted order
- Print Binary Tree levels in sorted order | Set 3 (Tree given as array)
- Print even positioned nodes of even levels in level order of the given binary tree
- Print all nodes between two given levels in Binary Tree
- Print Levels of all nodes in a Binary Tree
- Print a Binary Tree in Vertical Order | Set 3 (Using Level Order Traversal)
- Print a Binary Tree in Vertical Order | Set 1
- Print a Binary Tree in Vertical Order | Set 2 (Map based Method)
- Print extreme nodes of each level of Binary Tree in alternate order
- Recursive Program to Print extreme nodes of each level of Binary Tree in alternate order
- Print the nodes at odd levels of a tree
- Averages of Levels in Binary Tree
- Maximum sum of leaf nodes among all levels of the given binary tree
- Maximum sum of non-leaf nodes among all levels of the given binary tree
- Reverse alternate levels of a perfect binary tree
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : SHUBHAMSINGH10