# Check if a binary tree is sorted level-wise or not

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

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

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

 `// CPP program to determine whether ` `// binary tree is level sorted or not. ` ` `  `#include ` `using` `namespace` `std; ` ` `  `// Structure of a tree node. ` `struct` `Node { ` `    ``int` `key; ` `    ``Node *left, *right; ` `}; ` ` `  `// Function to create new tree node. ` `Node* newNode(``int` `key) ` `{ ` `    ``Node* temp = ``new` `Node; ` `    ``temp->key = key; ` `    ``temp->left = temp->right = NULL; ` `    ``return` `temp; ` `} ` ` `  `// Function to determine if ` `// given binary tree is level sorted ` `// or not. ` `int` `isSorted(Node* root) ` `{ ` ` `  `    ``// to store maximum value of previous ` `    ``// level. ` `    ``int` `prevMax = INT_MIN; ` ` `  `    ``// to store minimum value of current ` `    ``// level. ` `    ``int` `minval; ` ` `  `    ``// to store maximum value of current ` `    ``// level. ` `    ``int` `maxval; ` ` `  `    ``// to store number of nodes in current ` `    ``// level. ` `    ``int` `levelSize; ` ` `  `    ``// queue to perform level order traversal. ` `    ``queue q; ` `    ``q.push(root); ` ` `  `    ``while` `(!q.empty()) { ` ` `  `        ``// find number of nodes in current ` `        ``// level. ` `        ``levelSize = q.size(); ` ` `  `        ``minval = INT_MAX; ` `        ``maxval = INT_MIN; ` ` `  `        ``// traverse current level and find ` `        ``// minimum and maximum value of ` `        ``// this level. ` `        ``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 minimum value of this level ` `        ``// is not greater than maximum ` `        ``// value of previous level then ` `        ``// given tree is not level sorted. ` `        ``if` `(minval <= prevMax) ` `            ``return` `0; ` ` `  `        ``// maximum value of this level is ` `        ``// previous maximum value for ` `        ``// next level. ` `        ``prevMax = maxval; ` `    ``} ` ` `  `    ``return` `1; ` `} ` ` `  `// Driver program ` `int` `main() ` `{ ` `    ``/* ` `            ``1  ` `           ``/  ` `          ``4    ` `           ``\ ` `            ``6 ` `           ``/ \ ` `          ``8   9 ` `         ``/     \ ` `        ``12     10 ` `    ``*/` ` `  `    ``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

 `// Java program to determine whether  ` `// binary tree is level sorted or not.  ` `import` `java.util.*; ` ` `  `class` `GfG {  ` ` `  `// Structure of a tree node.  ` `static` `class` `Node {  ` `    ``int` `key;  ` `    ``Node left, right;  ` `} ` ` `  `// Function to create new tree node.  ` `static` `Node newNode(``int` `key)  ` `{  ` `    ``Node temp = ``new` `Node();  ` `    ``temp.key = key;  ` `    ``temp.left = ``null``; ` `    ``temp.right = ``null``;  ` `    ``return` `temp;  ` `}  ` ` `  `// Function to determine if  ` `// given binary tree is level sorted  ` `// or not.  ` `static` `int` `isSorted(Node root)  ` `{  ` ` `  `    ``// to store maximum value of previous  ` `    ``// level.  ` `    ``int` `prevMax = Integer.MIN_VALUE;  ` ` `  `    ``// to store minimum value of current  ` `    ``// level.  ` `    ``int` `minval;  ` ` `  `    ``// to store maximum value of current  ` `    ``// level.  ` `    ``int` `maxval;  ` ` `  `    ``// to store number of nodes in current  ` `    ``// level.  ` `    ``int` `levelSize;  ` ` `  `    ``// queue to perform level order traversal.  ` `    ``Queue q = ``new` `LinkedList ();  ` `    ``q.add(root);  ` ` `  `    ``while` `(!q.isEmpty()) {  ` ` `  `        ``// find number of nodes in current  ` `        ``// level.  ` `        ``levelSize = q.size();  ` ` `  `        ``minval = Integer.MAX_VALUE;  ` `        ``maxval = Integer.MIN_VALUE;  ` ` `  `        ``// traverse current level and find  ` `        ``// minimum and maximum value of  ` `        ``// this level.  ` `        ``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 minimum value of this level  ` `        ``// is not greater than maximum  ` `        ``// value of previous level then  ` `        ``// given tree is not level sorted.  ` `        ``if` `(minval <= prevMax)  ` `            ``return` `0``;  ` ` `  `        ``// maximum value of this level is  ` `        ``// previous maximum value for  ` `        ``// next level.  ` `        ``prevMax = maxval;  ` `    ``}  ` ` `  `    ``return` `1``;  ` `}  ` ` `  `// Driver program  ` `public` `static` `void` `main(String[] args)  ` `{  ` `    ``/*  ` `            ``1  ` `        ``/  ` `        ``4  ` `        ``\  ` `            ``6  ` `        ``/ \  ` `        ``8 9  ` `        ``/     \  ` `        ``12     10  ` `    ``*/` ` `  `    ``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

 `# Python3 program to determine whether  ` `# binary tree is level sorted or not.  ` `from` `queue ``import` `Queue ` ` `  `# Function to create new tree node.  ` `class` `newNode: ` `    ``def` `__init__(``self``, key):  ` `        ``self``.key ``=` `key  ` `        ``self``.left ``=` `self``.right ``=` `None` ` `  `# Function to determine if given binary ` `# tree is level sorted or not.  ` `def` `isSorted(root): ` ` `  `    ``# to store maximum value of previous  ` `    ``# level.  ` `    ``prevMax ``=` `-``999999999999` ` `  `    ``# to store minimum value of current  ` `    ``# level.  ` `    ``minval ``=` `None` ` `  `    ``# to store maximum value of current  ` `    ``# level.  ` `    ``maxval ``=` `None` ` `  `    ``# to store number of nodes in current  ` `    ``# level.  ` `    ``levelSize ``=` `None` ` `  `    ``# queue to perform level order traversal.  ` `    ``q ``=` `Queue() ` `    ``q.put(root)  ` ` `  `    ``while` `(``not` `q.empty()):  ` ` `  `        ``# find number of nodes in current  ` `        ``# level.  ` `        ``levelSize ``=` `q.qsize()  ` ` `  `        ``minval ``=` `999999999999` `        ``maxval ``=` `-``999999999999` ` `  `        ``# traverse current level and find  ` `        ``# minimum and maximum value of  ` `        ``# this level.  ` `        ``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 minimum value of this level  ` `        ``# is not greater than maximum  ` `        ``# value of previous level then  ` `        ``# given tree is not level sorted.  ` `        ``if` `(minval <``=` `prevMax):  ` `            ``return` `0` ` `  `        ``# maximum value of this level is  ` `        ``# previous maximum value for  ` `        ``# next level.  ` `        ``prevMax ``=` `maxval ` `    ``return` `1` ` `  `# Driver Code  ` `if` `__name__ ``=``=` `'__main__'``: ` `     `  `    ``#  ` `    ``#     1  ` `    ``#     /  ` `    ``#     4  ` `    ``#     \  ` `    ``#     6  ` `    ``#     / \  ` `    ``#     8 9  ` `    ``#     /     \  ` `    ``# 12     10  ` `    ``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"``) ` ` `  `# This code is contributed by PranchalK `

## C#

 `// C# program to determine whether  ` `// binary tree is level sorted or not.  ` `using` `System; ` `using` `System.Collections.Generic;  ` `     `  `class` `GFG  ` `{  ` ` `  `// Structure of a tree node.  ` `public` `class` `Node ` `{  ` `    ``public` `int` `key;  ` `    ``public` `Node left, right;  ` `} ` ` `  `// Function to create new tree node.  ` `static` `Node newNode(``int` `key)  ` `{  ` `    ``Node temp = ``new` `Node();  ` `    ``temp.key = key;  ` `    ``temp.left = ``null``; ` `    ``temp.right = ``null``;  ` `    ``return` `temp;  ` `}  ` ` `  `// Function to determine if  ` `// given binary tree is level sorted  ` `// or not.  ` `static` `int` `isSorted(Node root)  ` `{  ` ` `  `    ``// to store maximum value of previous  ` `    ``// level.  ` `    ``int` `prevMax = ``int``.MinValue;  ` ` `  `    ``// to store minimum value of current  ` `    ``// level.  ` `    ``int` `minval;  ` ` `  `    ``// to store maximum value of current  ` `    ``// level.  ` `    ``int` `maxval;  ` ` `  `    ``// to store number of nodes in current  ` `    ``// level.  ` `    ``int` `levelSize;  ` ` `  `    ``// queue to perform level order traversal.  ` `    ``Queue q = ``new` `Queue ();  ` `    ``q.Enqueue(root);  ` ` `  `    ``while` `(q.Count != 0)  ` `    ``{  ` ` `  `        ``// find number of nodes in current  ` `        ``// level.  ` `        ``levelSize = q.Count;  ` ` `  `        ``minval = ``int``.MaxValue;  ` `        ``maxval = ``int``.MinValue;  ` ` `  `        ``// traverse current level and find  ` `        ``// minimum and maximum value of  ` `        ``// this level.  ` `        ``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 minimum value of this level  ` `        ``// is not greater than maximum  ` `        ``// value of previous level then  ` `        ``// given tree is not level sorted.  ` `        ``if` `(minval <= prevMax)  ` `            ``return` `0;  ` ` `  `        ``// maximum value of this level is  ` `        ``// previous maximum value for  ` `        ``// next level.  ` `        ``prevMax = maxval;  ` `    ``}  ` ` `  `    ``return` `1;  ` `}  ` ` `  `// Driver Code ` `public` `static` `void` `Main(String[] args)  ` `{  ` `    ``/*  ` `            ``1  ` `        ``/  ` `        ``4  ` `        ``\  ` `            ``6  ` `        ``/ \  ` `        ``8 9  ` `        ``/     \  ` `        ``12     10  ` `    ``*/` `    ``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"``);  ` `} ` `}  ` ` `  `// This code is contributed by PrinciRaj1992  `

Output:

```Sorted
```

Time Complexity: O(n)
Auxiliary Space: O(n)

My Personal Notes arrow_drop_up A Programmer and A Machine learning Enthusiast

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.

Article Tags :
Practice Tags :

Be the First to upvote.

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.