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 :
- Start level order traversal of tree.
- Store all the nodes in a set(or any other similar data structures).
- Print elements of set.
Implementation:
C++
// CPP code to print level order
// traversal in sorted order
#include <bits/stdc++.h>
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<Node*> 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;
}
Java
// Java code to print level order
// traversal in sorted order
import java.util.*;
import java.util.HashSet;
class GFG
{
static class Node
{
int data;
Node left, right;
};
static Node newNode(int data)
{
Node node = new Node();
node.data = data;
node.left = node.right = null;
return (node);
}
// Function to print sorted
// level order traversal
static void sorted_level_order(Node root)
{
Queue<Node> q = new LinkedList<>();
Set<Integer> s = new HashSet<Integer>();
q.add(root);
q.add(null);
while (!q.isEmpty())
{
Node tmp = q.peek();
q.remove();
if (tmp == null)
{
if (s.isEmpty())
break;
Iterator value = s.iterator();
while (value.hasNext())
{
System.out.print(value.next() + " ");
}
q.add(null);
s.clear();
}
else
{
s.add(tmp.data);
if (tmp.left != null)
q.add(tmp.left);
if (tmp.right != null)
q.add(tmp.right);
}
}
}
// Driver Code
public static void main(String[] args)
{
Node 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 SHUBHAMSINGH10
Python3
# Python3 program to print level order
# traversal in sorted order
# Helper function that allocates a new
# node with the given data and None
# left and right pointers.
class newNode:
# Construct to create a new node
def __init__(self, key):
self.data = key
self.left = None
self.right = None
# Function to print sorted
# level order traversal
def sorted_level_order( root):
q = []
s = set()
q.append(root)
q.append(None)
while (len(q)):
tmp = q[0]
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)
C#
// C# code to print level order
// traversal in sorted order
using System;
using System.Collections.Generic;
class GFG
{
public class Node
{
public int data;
public Node left, right;
};
static Node newNode(int data)
{
Node node = new Node();
node.data = data;
node.left = node.right = null;
return (node);
}
// Function to print sorted
// level order traversal
static void sorted_level_order(Node root)
{
Queue<Node> q = new Queue<Node>();
SortedSet<int> s = new SortedSet<int>();
q.Enqueue(root);
q.Enqueue(null);
while (q.Count != 0)
{
Node tmp = q.Peek();
q.Dequeue();
if (tmp == null)
{
if (s.Count == 0)
break;
foreach (int v in s)
{
Console.Write(v + " ");
}
q.Enqueue(null);
s.Clear();
}
else
{
s.Add(tmp.data);
if (tmp.left != null)
q.Enqueue(tmp.left);
if (tmp.right != null)
q.Enqueue(tmp.right);
}
}
}
// Driver Code
public static void Main(String[] args)
{
Node 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 29AjayKumar
JavaScript
<script>
// Javascript code to print level order
// traversal in sorted order
var SortedSet = require("collections/sorted-set");
class Node
{
constructor()
{
this.data=0;
this.left=this.right=null;
}
}
function newNode(data)
{
let node = new Node();
node.data = data;
node.left = node.right = null;
return (node);
}
// Function to print sorted
// level order traversal
function sorted_level_order(root)
{
let q = [];
let s = new SortedSet();
q.push(root);
q.push(null);
while (q.length!=0)
{
let tmp = q.shift();
if (tmp == null)
{
if (s.size==0)
break;
for(let i of s.values())
{
document.write(i+" ");
}
q.push(null);
s.clear();
}
else
{
s.add(tmp.data);
if (tmp.left != null)
q.push(tmp.left);
if (tmp.right != null)
q.push(tmp.right);
}
}
}
// Driver Code
let 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 rag2127
</script>
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.
Similar Reads
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 1Output : 75 61 2 3 4 Input : 7 / \ 16 1 / \ 4 13 Output :7 1 164 13Recommended PracticePrint Binary Tree levels in sorted orderTry It!Here we can use two Priority queue for print in sor
9 min read
Print Binary Tree levels in sorted order | Set 3 (Tree given as array) Given a Complete Binary Tree as an array, the task is to print all of its levels in sorted order.Examples: Input: arr[] = {7, 6, 5, 4, 3, 2, 1} The given tree looks like 7 / \ 6 5 / \ / \ 4 3 2 1 Output: 7 5 6 1 2 3 4 Input: arr[] = {5, 6, 4, 9, 2, 1} The given tree looks like 5 / \ 6 4 / \ / 9 2 1
6 min read
Perfect Binary Tree Specific Level Order Traversal | Set 2 Perfect Binary Tree using Specific Level Order Traversal in Set 1. The earlier traversal was from Top to Bottom. In this post, Bottom to Top traversal (asked in Amazon Interview | Set 120 â Round 1) is discussed. 16 31 17 30 18 29 19 28 20 27 21 26 22 25 23 24 8 15 9 14 10 13 11 12 4 7 5 6 2 3 1The
15+ min read
Level of Each node in a Tree from source node (using BFS) Given a tree with v vertices, find the level of each node in a tree from the source node. Examples: Input : Output : Node Level 0 0 1 1 2 1 3 2 4 2 5 2 6 2 7 3 Explanation : Input: Output : Node Level 0 0 1 1 2 1 3 2 4 2 Explanation: Approach: BFS(Breadth-First Search) is a graph traversal technique
8 min read
Level Order Successor of a node in Binary Tree Given a binary tree and a node in the binary tree, find Levelorder successor of the given node. That is, the node that appears after the given node in the level order traversal of the tree. Note: The task is not just to print the data of the node, you have to return the complete node from the tree.
9 min read