Program to check whether a binary tree is BST or not in Python

A Binary Search Tree (BST) is a binary tree with specific ordering properties. We can check if a binary tree is a valid BST by performing an inorder traversal and verifying the result is sorted.

BST Properties

A valid BST must satisfy these conditions −

  • All nodes in the left subtree are smaller than the current node value
  • All nodes in the right subtree are larger than the current node value
  • These properties hold recursively for all nodes
5 1 9 7 10 Valid BST: Inorder = [1, 5, 7, 9, 10]

Algorithm

The approach uses inorder traversal properties −

  • Perform inorder traversal to get node values in sequence
  • If the sequence is sorted in ascending order, the tree is a valid BST
  • Return the comparison result

Implementation

class TreeNode:
    def __init__(self, data, left=None, right=None):
        self.data = data
        self.left = left
        self.right = right

class Solution:
    def solve(self, root):
        def inorder(root, values):
            if root is None:
                return
            inorder(root.left, values)
            values.append(root.data)
            inorder(root.right, values)
        
        values = []
        inorder(root, values)
        return values == sorted(values)

# Create the BST
root = TreeNode(5)
root.left = TreeNode(1)
root.right = TreeNode(9)
root.right.left = TreeNode(7)
root.right.right = TreeNode(10)

# Check if it's a valid BST
ob = Solution()
result = ob.solve(root)
print(f"Is valid BST: {result}")
Is valid BST: True

Testing with Invalid BST

Let's test with an invalid BST where the ordering property is violated ?

# Create an invalid BST
invalid_root = TreeNode(5)
invalid_root.left = TreeNode(1)
invalid_root.right = TreeNode(4)  # Invalid: 4 < 5 but in right subtree
invalid_root.right.left = TreeNode(3)
invalid_root.right.right = TreeNode(6)

ob = Solution()
result = ob.solve(invalid_root)
print(f"Is valid BST: {result}")

# Show the inorder traversal
def get_inorder(root):
    values = []
    def inorder(node):
        if node:
            inorder(node.left)
            values.append(node.data)
            inorder(node.right)
    inorder(root)
    return values

inorder_sequence = get_inorder(invalid_root)
print(f"Inorder traversal: {inorder_sequence}")
print(f"Sorted version: {sorted(inorder_sequence)}")
Is valid BST: False
Inorder traversal: [1, 3, 4, 5, 6]
Sorted version: [1, 3, 4, 5, 6]

How It Works

The algorithm leverages the key property of BSTs: an inorder traversal of a valid BST produces values in ascending order. By comparing the inorder sequence with its sorted version, we can determine if the BST property holds.

Time and Space Complexity

  • Time Complexity: O(n) for traversal + O(n log n) for sorting = O(n log n)
  • Space Complexity: O(n) for storing the inorder sequence

Conclusion

This method effectively validates BST properties by using inorder traversal. The sorted sequence check ensures all BST ordering constraints are satisfied across the entire tree structure.

Updated on: 2026-03-25T10:49:55+05:30

728 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements