Check if an array represents Inorder of Binary Search tree or not in Python



The Binary Search Tree (BST) is a widely used data structure that maintains the elements in a sorted hierarchical order. Each node in the BST follows the specific property:

  • The values in the left subtree are always less than the values of the current node.
  • The values in the right subtree are always greater than the node.

In this article, we are going to learn about checking if an array represents the inorder of a BST or not in Python.

Checking for inorder of the BST

Inorder traversal is the common way to access the elements of the BST, which processes the left subtree, then the current node, and finally the right subtree. The inorder traversal on a BST always produces the sequence of elements in strictly increasing order.

To check if the given array represents the inorder traversal of the BST, we need to check if the array is sorted in ascending order without any duplicate values. If it satisfies the condition, then the array represents a valid inorder traversal of a BST. For example, let's consider the scenario where we are going to build a BST that gives the exact array when traversed inorder.

Scenario

The following is an example scenario:

Input: array = [2, 5, 7, 10, 20, 30]
Output: True
Explanation: 
Inorder traversal always visits nodes in the order (Left subtree->node->Right subtree):
Start at node (10).
Go to left subtree of 10->5
Go to left of 5 -> 2 -> print 2
Back to 5 -> print 5
Go to right of 5 -> 7 -> print 7
Back to 10 -> print 10
Go to right of 10 -> 20
Go to right of 20 -> 30 -> print 30

Example 1

In the following example, we are going to consider the array= [2, 5, 7, 10, 20, 30] and check whether it is an inorder of a BST or not:

def demo(array):
   for i in range(1, len(array)):
      if array[i] <= array[i - 1]:
         return False
   return True
array = [2, 5, 7, 10, 20, 30]
print(demo(array))

Following is the output of the above program:

True

Example 2

Let's look at the following example, where we are going to consider the array with duplicate values and observe the output. Which gives false, because in BST, all elements must be unique:

def demo(array):
   for i in range(1, len(array)):
      if array[i] <= array[i - 1]:
         return False
   return True
array = [1,22,3,4,1]
print(demo(array))

If we run the above program, it will generate the following output:

False
Updated on: 2025-07-30T18:44:15+05:30

563 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements