Back

Binary Search Tree Operations

BST Selection

A basic binary search tree with a few nodes

Operation

Value between 1 and 999

Playback Controls

Step 1 of 1

Select a BST and operation to begin

Reference implementation of BST Operations. Select a language tab to view and copy the code.

class BST:
    def insert(self, root, val):
        if root is None:
            return TreeNode(val)        # create new node
        if val < root.val:
            root.left  = self.insert(root.left,  val)  # go left
        elif val > root.val:
            root.right = self.insert(root.right, val)  # go right
        return root                     # return unchanged node

    def search(self, root, val):
        if root is None:
            return None                 # not found
        if val == root.val:
            return root                 # found
        if val < root.val:
            return self.search(root.left,  val)  # search left
        return self.search(root.right, val)      # search right

    def delete(self, root, val):
        if root is None: return None
        if val < root.val:
            root.left  = self.delete(root.left,  val)
        elif val > root.val:
            root.right = self.delete(root.right, val)
        else:                           # found node to delete
            if not root.left:  return root.right  # only right child
            if not root.right: return root.left   # only left child
            min_node = self._find_min(root.right) # in-order successor
            root.val   = min_node.val
            root.right = self.delete(root.right, min_node.val)
        return root

Python — Code Walkthrough

  1. Insert — recursive descent

    if val < root.val: root.left = self.insert(root.left, val)

    Compares val with the current node: go left if smaller, right if larger. When a None slot is reached, a new node is created there.

  2. Search — O(log n) average

    if val == root.val: return root

    At each node, compare val with node.val. Equal → found; smaller → recurse left; larger → recurse right. Height of tree determines depth.

  3. Delete — three cases

    min_node = self._find_min(root.right)

    No children → remove directly. One child → replace with that child. Two children → replace value with in-order successor (smallest in right subtree), then delete the successor.

  4. In-order successor

    root.val = min_node.val; root.right = self.delete(root.right, min_node.val)

    Copy the in-order successor's value into the current node, then delete the successor from the right subtree (which has at most one child).