Binary Search Trees in Python
Chapter 48: Binary Search Trees
4 short lessons, with 3D animations, quizzes and coding tasks.
The lessons
The BST rule, and searching
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.
Inserting, and the three cases of deleting
To insert x, search for it and hang it as a new leaf where the search falls off the tree; to delete a node, take it off if it is a leaf, let its only child move up if it has one, and if it has two, replace its value with its successor's and delete the successor instead.
Inorder gives sorted order; checking that a tree is a BST
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.
Balance: why a lopsided tree becomes a linked list
A BST's shape depends on the order its values arrive in, and searches cost one comparison per level, so a tree is fast only when it is balanced: at every node, the two subtrees' heights differ by at most 1.