Python 3D Academyবাংলা

The BST rule, and searching

🌍 In real life. To find a name in a thick printed phone book you never read from the first page. You open it somewhere in the middle: if the name you want comes earlier in the alphabet, the second half is no use, so you go left; if it comes later, you go right. Each look throws away a big part of the book.

A binary search tree builds that decision into its shape. Each node is a place to open the book: smaller values hang to its left and bigger values to its right. To find a value you start at the top and go left or right at every node, and the path down is never longer than the tree is tall.

The idea in one sentence: in a binary search tree, every value in a node's left subtree is smaller than the node and every value in its right subtree is bigger, so to look for x you compare it with the node and go left if it is smaller, right if it is bigger, until you find it or run out of tree.

Its words:

  • BST rule: for every node, everything in its left subtree < node < everything in its right subtree (this course's trees hold each value once)
  • search path: the nodes visited on the way down
  • comparison: one check of x against a node's value; a search makes one per node on its path

How it works, step by step, looking for x:

  1. start at the root
  2. if x equals the node's value, it is found
  3. if x is smaller, it can only be in the left subtree: go left; if bigger, go right
  4. if there is no child on that side, x is not in the tree

Watch 4 travel down and be found in three comparisons, then 6 fall off the tree because 7 has no left child:

Why it is correct. At a node with value v, if x < v then x can't be anywhere in the right subtree, because the rule says everything there is bigger than v, and so bigger than x. So going left loses nothing: if x is in the tree at all, it is in the left subtree. The same holds the other way round. Each step keeps the only part that could still hold x, exactly like binary search on a sorted list (Chapter 43), and when the side we need is empty, nothing is left that could hold x.

What it costs, by counting. A search makes one comparison per node on its path, so at most h comparisons, where h is the tree's height: O(h). How big h is depends on the shape:

  • a well-balanced tree with n nodes has about log₂ n levels: 7 nodes → 3, 1,023 nodes → 10, about 1,000,000 nodes → 20
  • a tree that is one long chain has n levels: a million nodes means up to a million comparisons

So a BST search is O(log n) when the tree is balanced and O(n) when it is not; Lesson 48.4 is about keeping it balanced.

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

def bst_contains(root, x):
    node = root
    while node is not None:
        if x == node.val:
            return True
        if x < node.val:
            node = node.left          # x can only be on the left
        else:
            node = node.right         # x can only be on the right
    return False                      # fell off the tree: not there

root = Node(5, Node(3, Node(1), Node(4)), Node(8, Node(7), Node(9)))
print(bst_contains(root, 4), bst_contains(root, 6))

# the same search, written recursively
def search(node, x):
    if node is None:
        return False
    if x == node.val:
        return True
    return search(node.left, x) if x < node.val else search(node.right, x)

print(search(root, 9), search(root, 10))

Mistakes and edge cases.

  • going the wrong way: swap left and right and every search for a value that isn't at the root fails; smaller values are always on the left
  • no check for None: walking off the tree gives AttributeError: 'NoneType' object has no attribute 'val'; the loop must stop when the node is None
  • searching both sides: that works, but it visits every node, O(n), and throws away the whole point of the rule
  • an empty tree: root = None contains nothing; the loop doesn't run and the answer is False
  • mixing types: a tree of numbers searched for "4" raises TypeError, because "4" < 5 can't be compared

Quiz

  1. Which nodes does the search for 7 visit?

    class Node:
        def __init__(self, val, left=None, right=None):
            self.val = val
            self.left = left
            self.right = right
    
    root = Node(5, Node(3, Node(1), Node(4)), Node(8, Node(7), Node(9)))
    path, node = [], root
    while node is not None:
        path.append(node.val)
        if node.val == 7:
            break
        node = node.left if 7 < node.val else node.right
    print(path)
  2. Which of these level-order trees is a binary search tree?

    • [5, 3, 8, 1, 4, 7, 9]
    • [5, 3, 8, 1, 6, 7, 9]
    • [5, 8, 3]
  3. A well-balanced BST holds about a million values. About how many comparisons does a search need at most?

    • About 20
    • About 1,000
    • About 500,000
  4. This only finds the root's value; every other search returns False. Which line is wrong?

    def bst_contains(root, x):
        node = root
        while node is not None:
            if x == node.val:
                return True
            node = node.right if x < node.val else node.left
        return False
  5. Values 1, 2, 3, …, 100 were inserted in that order, so the BST is one long chain. How many comparisons does searching for 100 take?

    • 100
    • About 7
    • 1

Coding tasks

  1. Write bst_contains(root, x): True if x is in the binary search tree, otherwise False. Go left or right at each node; don't look at both sides.

  2. A shop keeps its prices in a BST. Write closest(root, x): the price nearest to x (if two are equally near, the smaller one). The tree is never empty. Follow the search path for x: the nearest value is always on it.

  3. Make the cost concrete. Write count_steps(root, x): how many nodes a search for x compares it with, counting the node where it is found, or every node on the path if it is not there (0 for an empty tree).