Search follows the rule
After this: Follow a search and count its comparisons: depth + 1 to find a key.
On this page · 6 sections · 3 checks
In The order rule and The full rule you found numbers by hand, turning left or right at each node. This lesson writes that method down as clear steps, counts the work it takes, and then turns it into code.
The steps of a search
Here is the method in words.
- Start at the root.
- Compare the key you want with the key in the node. If they are equal, you have found it, so stop.
- If the key you want is smaller, go to the left child. If it is larger, go to the right child.
- If there is no child on that side, the key is not in the tree, so stop. Otherwise, go back to step 2.
Here is the example tree again.
This is the search for 40.
| Node | Compare | What happens |
|---|---|---|
| 50 | 40 with 50 | 40 is smaller, so go left |
| 30 | 40 with 30 | 40 is larger, so go right |
| 40 | 40 with 40 | They are equal, so 40 is found |
This is the search for 45, which is not in the tree.
| Node | Compare | What happens |
|---|---|---|
| 50 | 45 with 50 | 45 is smaller, so go left |
| 30 | 45 with 30 | 45 is larger, so go right |
| 40 | 45 with 40 | 45 is larger, so go right, but nothing is there |
Both searches made three comparisons and looked at the same three nodes. The search for 45 can safely answer "no", because each comparison ruled out part of the tree. After the left turn at 50, the right side of 50 could not hold 45. After the right turn at 30, 20 could not be 45. That left only the spot to the right of 40, and that spot is empty.
Counting comparisons
Each comparison moves the search one level down the tree. So the number of comparisons depends on how far down the key sits.
The of a node says how many steps down from the root it is. The root is at depth 0. Here is every key in the example tree.
| Key | Depth | Comparisons to find it |
|---|---|---|
| 50 | 0 | 1 |
| 30, 70 | 1 | 2 |
| 20, 40, 60, 80 | 2 | 3 |
The number of comparisons is always one more than the depth. So a key at depth d takes d + 1 comparisons. There is one comparison for each step down, and one more for the node where the key is found.
The of a tree is the depth of its deepest node. The example tree has height 2. A path cannot go deeper than that, so a search never needs more than height + 1 comparisons, whether or not it finds the key. This is the : the most work a search can ever need.
Programmers write this cost as O(h), where h is the height. It means that the work grows with the height of the tree, and not directly with the number of keys. If this notation is new to you, Counting steps explains it, starting from O(1) and O(n). A later lesson shows why the height matters so much.
The code
Here is the same method in code. It is the start of a BST class, which later lessons add to.
class BST: def __init__(self): self.root = None
def search(self, key): node = self.root while node is not None: # one comparison per level if key == node.key: return True node = node.left if key < node.key else node.right return False
def path(self, key): """The keys compared while searching for key, in order.""" keys = [] node = self.root while node is not None: keys.append(node.key) if key == node.key: break node = node.left if key < node.key else node.right return keysimport java.util.*;
public class BST { Node root;
boolean search(int key) { Node node = root; while (node != null) { // one comparison per level if (key == node.key) return true; node = key < node.key ? node.left : node.right; } return false; }
/** The keys compared while searching for key, in order. */ List<Integer> path(int key) { List<Integer> keys = new ArrayList<>(); Node node = root; while (node != null) { keys.add(node.key); if (key == node.key) break; node = key < node.key ? node.left : node.right; } return keys; }}Here is how to read it.
rootholds the root node. It is Nonenull while the tree is empty.- In
search, the variablenodeis the node we are at now. The loop runs untilnodebecomes Nonenull, which means there was no child on the side we took. - The highlighted lines are the whole method. If the keys are equal, the key is found. If not, the line with
key < node.keymoves to the left child when the key is smaller, and to the right child otherwise. - If the loop ends, the key was not found.
pathis the same loop. It also keeps a list of the keys it compared, so that we can print them. These are the nodes the visualizer highlights.
The next block builds the example tree by hand, then searches for 40 and for 45.
t = BST()t.root = Node(50)t.root.left, t.root.right = Node(30), Node(70)t.root.left.left, t.root.left.right = Node(20), Node(40)t.root.right.left, t.root.right.right = Node(60), Node(80)print(t.search(40), t.path(40))print(t.search(45), t.path(45))True [50, 30, 40] False [50, 30, 40]
BST t = new BST();t.root = new Node(50);t.root.left = new Node(30);t.root.right = new Node(70);t.root.left.left = new Node(20);t.root.left.right = new Node(40);t.root.right.left = new Node(60);t.root.right.right = new Node(80);System.out.println(t.search(40) + " " + t.path(40));System.out.println(t.search(45) + " " + t.path(45));true [50, 30, 40] false [50, 30, 40]
Both searches compare the same three keys. The first one ends on a match. The second one finds nothing where it wanted to go next.
Watch it happen
Here are four searches. Watch the comparison counter, and compare it with the depth of the key.
- Search for 40Search for 40. The search compares 50, then 30, then 40. Watch the comparison counter reach 3.
- Search for 80
- Search for 45
- Search for 50
Run an operation to begin.
Check yourself
You search for 80 in the example tree. How many comparisons does it take, and why?
You search for 45 in the example tree. What happens?
What does this print?
t = BST()t.root = Node(50)t.root.left, t.root.right = Node(30), Node(70)t.root.left.left, t.root.left.right = Node(20), Node(40)t.root.right.left, t.root.right.right = Node(60), Node(80)print(t.search(40), t.path(40))print(t.search(45), t.path(45))BST t = new BST();t.root = new Node(50);t.root.left = new Node(30);t.root.right = new Node(70);t.root.left.left = new Node(20);t.root.left.right = new Node(40);t.root.right.left = new Node(60);t.root.right.right = new Node(80);System.out.println(t.search(40) + " " + t.path(40));System.out.println(t.search(45) + " " + t.path(45));Connect
- Follow a search: compare, then go left or right, one level for each comparison.
- Count the comparisons: a key at depth d takes d + 1, and a key that is not there takes one for each node on the path.
- Say that the cost is O(h), which grows with the height, and that a search never needs more than h + 1 comparisons.