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

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
```

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

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.

## C++

 `// CPP code to print level order  ` `// traversal in sorted order ` `#include ` `using` `namespace` `std; ` ` `  `struct` `Node { ` `    ``int` `data; ` `    ``Node* left; ` `    ``Node* right; ` `    ``Node(``int` `dat = 0) ` `        ``: data(dat), left(nullptr),  ` `          ``right(nullptr) ` `    ``{ ` `    ``} ` `}; ` ` `  `// Function to print sorted  ` `// level order traversal ` `void` `sorted_level_order(Node* root) ` `{ ` `    ``queue q; ` `    ``set<``int``> s; ` ` `  `    ``q.push(root); ` `    ``q.push(nullptr); ` ` `  `    ``while` `(q.empty() == ``false``) { ` `        ``Node* tmp = q.front(); ` `        ``q.pop(); ` ` `  `        ``if` `(tmp == nullptr) { ` `            ``if` `(s.empty() == ``true``) ` `                ``break``; ` `            ``for` `(set<``int``>::iterator it = ` `                 ``s.begin();it != s.end(); ++it)  ` `                ``cout << *it << ``" "``; ` `            ``q.push(nullptr); ` `            ``s.clear(); ` `        ``} ` `        ``else` `{ ` `            ``s.insert(tmp->data); ` ` `  `            ``if` `(tmp->left != nullptr) ` `                ``q.push(tmp->left); ` `            ``if` `(tmp->right != nullptr) ` `                ``q.push(tmp->right); ` `        ``} ` `    ``} ` `} ` ` `  `// Driver code ` `int` `main() ` `{ ` `    ``Node* root = ``new` `Node(7); ` `    ``root->left = ``new` `Node(6); ` `    ``root->right = ``new` `Node(5); ` `    ``root->left->left = ``new` `Node(4); ` `    ``root->left->right = ``new` `Node(3); ` `    ``root->right->left = ``new` `Node(2); ` `    ``root->right->right = ``new` `Node(1);     ` `    ``sorted_level_order(root);     ` `    ``return` `0;     ` `} `

## Python3

# 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.
class newNode:

# 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()

q.append(root)
q.append(None)

while (len(q)):
tmp = q
q.pop(0)

if (tmp == None):
if (not len(s)):
break
for i in s:
print(i, end = ” “)
q.append(None)
s = set()

else :
s.add(tmp.data)

if (tmp.left != None):
q.append(tmp.left)
if (tmp.right != None):
q.append(tmp.right)

# 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)
sorted_level_order(root)

# This code is contributed by
# Shubham Singh(SHUBHAMSINGH10)

Output:

```7 5 6 1 2 3 4
```

My Personal Notes arrow_drop_up Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.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