Check if a binary tree is sorted level-wise or not
Last Updated :
23 Jun, 2021
Given a binary tree. The task is to check if the binary tree is sorted level-wise or not. A binary tree is level sorted if max( i-1th level) is less than min( ith level ).
Examples:
Input : 1
/ \
/ \
2 3
/ \ / \
/ \ / \
4 5 6 7
Output : Sorted
Input: 1
/
4
/ \
6 5
\
2
Output: Not sorted
Simple Solution: A simple solution is to compare minimum and maximum value of each adjacent level i and i+1. Traverse to ith and i+1th level, compare the minimum value of i+1th level with maximum value of ith level and return the result.
Time complexity: O(n2).
Efficient Solution: An efficient solution is to do level order traversal and keep track of the minimum and maximum values of current level. Use a variable prevMax to store the maximum value of the previous level. Then compare the minimum value of current level with the maximum value of the previous level, pevMax. If minimum value is greater than the prevMax, then the given tree is sorted level-wise up to current level. For next level, prevMax is the equal to maximum value of current level. So update the prevMax with maximum value of current level. Repeat this until all levels of given tree are not traversed.
Below is the implementation of above approach:
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int key;
Node *left, *right;
};
Node* newNode( int key)
{
Node* temp = new Node;
temp->key = key;
temp->left = temp->right = NULL;
return temp;
}
int isSorted(Node* root)
{
int prevMax = INT_MIN;
int minval;
int maxval;
int levelSize;
queue<Node*> q;
q.push(root);
while (!q.empty()) {
levelSize = q.size();
minval = INT_MAX;
maxval = INT_MIN;
while (levelSize > 0) {
root = q.front();
q.pop();
levelSize--;
minval = min(minval, root->key);
maxval = max(maxval, root->key);
if (root->left)
q.push(root->left);
if (root->right)
q.push(root->right);
}
if (minval <= prevMax)
return 0;
prevMax = maxval;
}
return 1;
}
int main()
{
Node* root = newNode(1);
root->left = newNode(4);
root->left->right = newNode(6);
root->left->right->left = newNode(8);
root->left->right->right = newNode(9);
root->left->right->left->left = newNode(12);
root->left->right->right->right = newNode(10);
if (isSorted(root))
cout << "Sorted" ;
else
cout << "Not sorted" ;
return 0;
}
|
Java
import java.util.*;
class GfG {
static class Node {
int key;
Node left, right;
}
static Node newNode( int key)
{
Node temp = new Node();
temp.key = key;
temp.left = null ;
temp.right = null ;
return temp;
}
static int isSorted(Node root)
{
int prevMax = Integer.MIN_VALUE;
int minval;
int maxval;
int levelSize;
Queue<Node> q = new LinkedList<Node> ();
q.add(root);
while (!q.isEmpty()) {
levelSize = q.size();
minval = Integer.MAX_VALUE;
maxval = Integer.MIN_VALUE;
while (levelSize > 0 ) {
root = q.peek();
q.remove();
levelSize--;
minval = Math.min(minval, root.key);
maxval = Math.max(maxval, root.key);
if (root.left != null )
q.add(root.left);
if (root.right != null )
q.add(root.right);
}
if (minval <= prevMax)
return 0 ;
prevMax = maxval;
}
return 1 ;
}
public static void main(String[] args)
{
Node root = newNode( 1 );
root.left = newNode( 4 );
root.left.right = newNode( 6 );
root.left.right.left = newNode( 8 );
root.left.right.right = newNode( 9 );
root.left.right.left.left = newNode( 12 );
root.left.right.right.right = newNode( 10 );
if (isSorted(root) == 1 )
System.out.println( "Sorted" );
else
System.out.println( "Not sorted" );
}
}
|
Python3
from queue import Queue
class newNode:
def __init__( self , key):
self .key = key
self .left = self .right = None
def isSorted(root):
prevMax = - 999999999999
minval = None
maxval = None
levelSize = None
q = Queue()
q.put(root)
while ( not q.empty()):
levelSize = q.qsize()
minval = 999999999999
maxval = - 999999999999
while (levelSize > 0 ):
root = q.queue[ 0 ]
q.get()
levelSize - = 1
minval = min (minval, root.key)
maxval = max (maxval, root.key)
if (root.left):
q.put(root.left)
if (root.right):
q.put(root.right)
if (minval < = prevMax):
return 0
prevMax = maxval
return 1
if __name__ = = '__main__' :
root = newNode( 1 )
root.left = newNode( 4 )
root.left.right = newNode( 6 )
root.left.right.left = newNode( 8 )
root.left.right.right = newNode( 9 )
root.left.right.left.left = newNode( 12 )
root.left.right.right.right = newNode( 10 )
if (isSorted(root)):
print ( "Sorted" )
else :
print ( "Not sorted" )
|
C#
using System;
using System.Collections.Generic;
class GFG
{
public class Node
{
public int key;
public Node left, right;
}
static Node newNode( int key)
{
Node temp = new Node();
temp.key = key;
temp.left = null ;
temp.right = null ;
return temp;
}
static int isSorted(Node root)
{
int prevMax = int .MinValue;
int minval;
int maxval;
int levelSize;
Queue<Node> q = new Queue<Node> ();
q.Enqueue(root);
while (q.Count != 0)
{
levelSize = q.Count;
minval = int .MaxValue;
maxval = int .MinValue;
while (levelSize > 0)
{
root = q.Peek();
q.Dequeue();
levelSize--;
minval = Math.Min(minval, root.key);
maxval = Math.Max(maxval, root.key);
if (root.left != null )
q.Enqueue(root.left);
if (root.right != null )
q.Enqueue(root.right);
}
if (minval <= prevMax)
return 0;
prevMax = maxval;
}
return 1;
}
public static void Main(String[] args)
{
Node root = newNode(1);
root.left = newNode(4);
root.left.right = newNode(6);
root.left.right.left = newNode(8);
root.left.right.right = newNode(9);
root.left.right.left.left = newNode(12);
root.left.right.right.right = newNode(10);
if (isSorted(root) == 1)
Console.WriteLine( "Sorted" );
else
Console.WriteLine( "Not sorted" );
}
}
|
Javascript
<script>
class Node
{
constructor()
{
this .key = null ;
this .left = null ;
this .right = null ;
}
}
function newNode(key)
{
var temp = new Node();
temp.key = key;
temp.left = null ;
temp.right = null ;
return temp;
}
function isSorted(root)
{
var prevMax = -1000000000;
var minval;
var maxval;
var levelSize;
var q = [];
q.push(root);
while (q.length != 0)
{
levelSize = q.length;
minval = 1000000000;
maxval = -1000000000;
while (levelSize > 0)
{
root = q[0];
q.shift();
levelSize--;
minval = Math.min(minval, root.key);
maxval = Math.max(maxval, root.key);
if (root.left != null )
q.push(root.left);
if (root.right != null )
q.push(root.right);
}
if (minval <= prevMax)
return 0;
prevMax = maxval;
}
return 1;
}
var root = newNode(1);
root.left = newNode(4);
root.left.right = newNode(6);
root.left.right.left = newNode(8);
root.left.right.right = newNode(9);
root.left.right.left.left = newNode(12);
root.left.right.right.right = newNode(10);
if (isSorted(root) == 1)
document.write( "Sorted" );
else
document.write( "Not Sorted" );
</script>
|
Time Complexity: O(n)
Auxiliary Space: O(n)
Share your thoughts in the comments
Please Login to comment...