Chapter 10 · Simulation

Binary Search Tree Simulator

← Chapter 10

Search / operation path

—

Traversal result

—

Binary Search Tree Simulator

At every node, all values in the left subtree are smaller than the node and all values in the right subtree are larger. Search, insertion, deletion, predecessor, successor, minimum, maximum and the sorted traversal all follow from this ordering rule.

Controls

  • Type an integer and press Insert, Search, Delete, Predecessor or Successor; the nodes visited along the way are highlighted.
  • The traversal buttons animate the visiting order and write it into the traversal result box.
  • Load example, Random tree and Reset replace the tree; Stop animation interrupts a running operation.

BST concepts

  • Search decisions: at each node, equality ends the search; a smaller target goes left and a larger one goes right.
  • Predecessor and successor: the predecessor is the largest key smaller than the value, the successor the smallest key larger than it. Either may sit in a subtree or among the ancestors.
  • Deletion: a leaf is simply removed; a node with one child is replaced by that child; a node with two children takes the minimum of its right subtree (its inorder successor).
  • Degeneration: inserting values in sorted order builds a chain. The tree is still a valid BST, but its height, and with it the running time, becomes linear.

Traversal orders

TraversalOrderTypical use
InorderLeft, root, rightReading the values in sorted order.
PreorderRoot, left, rightSerializing or copying the tree structure.
PostorderLeft, right, rootDeleting or evaluating subtrees before their parent.
Level orderLevel by levelExamining the tree one level at a time.