Data Structures & Algorithms / Module 6: Trees
Topic 6.2
Binary search trees
Smaller on the left, bigger on the right: search and insert along one path.
Watch: every fork asks just one question: smaller or bigger? Each answer throws away a whole branch, so you only ever look along one path from the top down.
- the sign being looked at
- the way taken so far
- found / where it's stored
Binary search that can grow
Binary search in a sorted array is very fast for finding things, but inserting a new number in the middle of an array means shifting everything after it: O(n). A BST fixes that. Searching still drops half the possibilities at each step, and inserting just attaches a new node at the empty spot the search ends on.
Choose "insert 11" in the figure: the search ends at an empty spot, and that's where 11 goes. No other node moves.
Code, for programmersSearch and insert
function find(node, x) {
while (node) {
if (x === node.value) return node;
node = x < node.value ? node.left : node.right; // pick one side, skip the other
}
return null;
}
function insert(node, x) {
if (!node) return { value: x, left: null, right: null }; // the empty spot
if (x < node.value) node.left = insert(node.left, x);
else node.right = insert(node.right, x);
return node;
}How fast
The cost equals the tree's height. If the tree is bushy and balanced, a million nodes are only about 20 levels tall, so a search needs about 20 comparisons. But a plain BST doesn't look after its own shape. The next topic shows what happens when data arrives in a bad order.
Deleting
- A leaf: just remove it.
- One child: connect the child straight to the parent.
- Two children: replace the value with the smallest number on the right side (its successor in order), then delete that successor, which has at most one child.
Quiz
In a BST you are looking for 7 and are at node 10. Which way?
The cost of searching a BST is proportional to…
Which question suits a BST better than a hash map?
0 of 3 answered.