Binary Search Tree
Hierarchical search guided by an ordering invariant
Every comparison chooses one subtree
In a binary search tree (BST), every value in a node's left subtree is smaller and every value in its right subtree is larger. Searching compares the target with the current node and discards one entire subtree. Inorder traversal visits the values in ascending order.
Enter an integer from 1 to 99, then insert it to trace its path.
Search and insertion take O(h), where h is the tree height. A balanced tree has h = O(log n), but ordinary BST insertion does not guarantee that shape.
Shape controls performance
Inserting already sorted values can create a one-sided chain with height n. AVL trees and red-black trees rotate nodes to keep their height logarithmic while preserving the same ordering invariant. Compare the two shapes using exactly the same seven values.
Height 7 levels · worst-case search 7 comparisons(O(n), like a linked list)
Both trees contain 1 through 7. Search for 7 and compare the path lengths.
A heap keeps a weaker parent-child order to make the minimum or maximum easy to remove, while a BST supports ordered search.