Python 3D Academyবাংলা

Inorder gives sorted order; checking that a tree is a BST

🌍 In real life. A school keeps its exam marks in a binary search tree. At the end of term it needs the merit list from the lowest mark to the highest, and it gets it without sorting anything: it just walks the tree in the right order. But one day a new teacher hangs a mark in the wrong place. The tree still looks tidy, because every parent and child seem to be in order, yet searches start to miss marks that are really there.

This lesson shows both sides of one fact: walking a BST inorder visits its values from smallest to biggest, and that is also the surest way to check that a tree really is a BST.

The idea in one sentence: an inorder walk of a BST lists its values in increasing order, and a tree is a BST exactly when every value lies strictly between the lowest and highest values its position allows.

Its words:

  • inorder (Lesson 47.2): left subtree, node, right subtree
  • bounds: the range a node's value must be in, set by its ancestors: going left from v makes v the new upper bound, going right makes it the new lower bound
  • valid BST: a tree where every node is inside its bounds
  • k-th smallest: the value that comes k-th in the inorder walk (counting from 1)

How it works, step by step, for the inorder walk of the tree [5, 3, 8, 1, 4, 7, 9]:

  1. the walk goes left as far as it can before visiting anything: 1 comes first, the smallest
  2. after a node's whole left subtree (all smaller values) comes the node itself
  3. then its right subtree, all bigger values

Watch the order row come out sorted:

Now the broken tree [5, 3, 8, 1, 6]. Each parent and child look fine: 6 is bigger than its parent 3, so it is 3's right child. But 6 is in 5's left subtree, where everything must be smaller than 5. The inorder walk gives it away: 6 comes before 5, so the order is not sorted.

Why it is correct. In a BST, everything in a node's left subtree is smaller than it and everything in its right subtree is bigger. Inorder visits the whole left subtree, then the node, then the whole right subtree. So the node comes after every smaller value in its subtree and before every bigger one, and that is true at every node, so the whole list is sorted. To check a tree, comparing each node with its children is not enough, as 6 shows. Each node must be compared with all its ancestors, and the bounds do that cheaply. Going left from v says "everything below here must be smaller than v", and going right says "bigger than v". So carrying (low, high) down the tree checks every ancestor at once.

What it costs, by counting. The inorder walk and the bounds check each visit every node once: O(n). Inserting n values and then reading them back inorder sorts them (a tree sort): about n log₂ n comparisons when the tree stays balanced, but n(n − 1)/2 when the values arrive already sorted and the tree becomes a chain. The k-th smallest value with an early stop needs only O(h + k) steps: walk down to the smallest, then k − 1 more.

class Node:
    def __init__(self, val, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def is_bst(root):
    def ok(node, low, high):          # every value here must be strictly between low and high
        if node is None:
            return True
        if not (low < node.val < high):
            return False
        return ok(node.left, low, node.val) and ok(node.right, node.val, high)
    return ok(root, float("-inf"), float("inf"))

def kth_smallest(root, k):
    stack, node = [], root
    while stack or node is not None:
        while node is not None:       # go as far left as possible
            stack.append(node)
            node = node.left
        node = stack.pop()            # the next value in sorted order
        k -= 1
        if k == 0:
            return node.val
        node = node.right

good = Node(5, Node(3, Node(1), Node(4)), Node(8, Node(7), Node(9)))
bad = Node(5, Node(3, Node(1), Node(6)), Node(8))   # 6 is on the wrong side of 5
print(is_bst(good), is_bst(bad))
print(kth_smallest(good, 1), kth_smallest(good, 4))

Mistakes and edge cases.

  • checking only parent and child: it misses a value that is on the correct side of its parent but the wrong side of a grandparent, like 6 above
  • <= instead of <: with each value stored once, a value equal to a bound is a repeat and breaks the rule; keep the comparisons strict
  • bounds that are too small: starting with 0 or 1,000,000 as the bounds fails for negative or big values; float("-inf") and float("inf") compare correctly with every number
  • k out of range: asking for the 8th smallest of 7 values has no answer; decide what to return, or check k first
  • an empty tree: it is a valid BST, with nothing to break the rule

Quiz

  1. Values are inserted into an empty BST, then read inorder. What does this print?

    class Node:
        def __init__(self, val, left=None, right=None):
            self.val = val
            self.left = left
            self.right = right
    
    def insert(root, x):
        if root is None:
            return Node(x)
        if x < root.val:
            root.left = insert(root.left, x)
        else:
            root.right = insert(root.right, x)
        return root
    
    def inorder(node):
        return [] if node is None else inorder(node.left) + [node.val] + inorder(node.right)
    
    root = None
    for mark in [50, 30, 70, 20, 40]:
        root = insert(root, mark)
    print(inorder(root))
  2. This check only compares each node with its children. What does it say about the broken tree?

    class Node:
        def __init__(self, val, left=None, right=None):
            self.val = val
            self.left = left
            self.right = right
    
    def is_bst(node):
        if node is None:
            return True
        if node.left is not None and node.left.val > node.val:
            return False
        if node.right is not None and node.right.val < node.val:
            return False
        return is_bst(node.left) and is_bst(node.right)
    
    print(is_bst(Node(5, Node(3, Node(1), Node(6)), Node(8))))
  3. Checking with bounds, the node 4 in [5, 3, 8, 1, 4, 7, 9] (3's right child) must lie in which range?

    • Between 3 and 5
    • Bigger than 3, with no upper limit
    • Smaller than 5, with no lower limit
  4. With an early stop, how much work does finding the k-th smallest value take in a BST of height h?

    • O(h + k): down to the smallest, then k − 1 more steps of the inorder walk
    • O(n) always
    • O(1)
  5. This bounds check says the tree Node(2, Node(2)) is a BST, though 2 appears twice. Which line is wrong?

    def is_bst(root):
        def ok(node, low, high):
            if node is None:
                return True
            if not (low <= node.val <= high):
                return False
            return ok(node.left, low, node.val) and ok(node.right, node.val, high)
        return ok(root, float("-inf"), float("inf"))

Coding tasks

  1. This is_bst(root) only compares each node with its children, so it is fooled by a value on the wrong side of a grandparent. Fix it: return True only if every node is bigger than everything in its left subtree and smaller than everything in its right subtree (each value appears once).

  2. Write kth_smallest(root, k): the k-th smallest value in the BST, counting from 1 (so k = 1 is the smallest). k is always between 1 and the number of nodes.