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 ).
Input : 1
4 5 6 7
Output : Sorted
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:
# Python3 program to determine whether
# binary tree is level sorted or not.
from queue import Queue
# Function to create new tree node.
def __init__(self, key):
self.key = key
self.left = self.right = None
# Function to determine if given binary
# tree is level sorted or not.
# to store maximum value of previous
prevMax = -999999999999
# to store minimum value of current
minval = None
# to store maximum value of current
maxval = None
# to store number of nodes in current
levelSize = None
# queue to perform level order traversal.
q = Queue()
while (not q.empty()):
# find number of nodes in current
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
levelSize -= 1
minval = min(minval, root.key)
maxval = max(maxval, root.key)
# 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):
# maximum value of this level is
# previous maximum value for
# next level.
prevMax = maxval
# Driver Code
if __name__ == '__main__':
# 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)
# This code is contributed by PranchalK
Time Complexity: O(n)
Auxiliary Space: O(n)