6.5Binary Search Tree with Linked Nodes
Search: left or right?
Fast searching is the reason a binary search tree exists. The search you did in an array tree with index arithmetic, you will now do by following the left and right pointers. Each comparison rules out a whole subtree.
- How to compare the value with a node and go down to the left or the right
- The recursive and the loop version of the search
- Why the search time depends on the height of the tree
1Idea
The search starts at the root, and at every node one of three things happens. If the value equals the node's value, the search is over. If it is smaller, it can only be in the left subtree, because the BST rule puts larger values on the right. If it is larger, only the right subtree is checked. The other subtree is never entered.
This recipe repeats itself: searching the left subtree is the same search started at that subtree's root. That is why the code is short with recursion. The base case is an empty subtree: reaching NULL means the value is not in the tree.
Each call makes at most one call of its own, so the same work can be done with a loop. The loop version uses no call stack:
struct TreeNode* searchLoop(struct TreeNode* root, int value) { while (root != NULL && root->data != value) root = (value < root->data) ? root->left : root->right; return root; // the node found, or NULL}In an ordinary binary tree a search has to look into both subtrees and takes O(n). The BST rule cuts that down to a single path.
2Step by step
The drawing searches for 60 in a tree holding 50, 30, 70, 20, 40, 60 and 80. The orange node is the one being compared, and the stack on the right shows the open calls.
- Start.
rootpoints to 50. We will search for 60. - The first call starts at the root. 60 is not equal to 50 and is larger.
- Because it is larger, a new call opens on the right subtree. 30, 20 and 40 on the left are never looked at. 60 is smaller than 70.
- Because it is smaller, the search goes down to 60 on the left of 70. This is the third call.
- 60 equals the node's value: the search is over. This call returns the node's address.
- On the way back each call passes the address it got straight up. 60 was found with three comparisons.
struct TreeNode { int data; struct TreeNode* left; struct TreeNode* right;}; struct TreeNode* search(struct TreeNode* root, int value) { if (root == NULL) return NULL; // empty subtree: not found if (value == root->data) return root; // found if (value < root->data) return search(root->left, value); // smaller: go left return search(root->right, value); // larger: go right}class TreeNode { int data; TreeNode left, right; TreeNode(int data) { this.data = data; }} TreeNode search(TreeNode root, int value) { if (root == null) return null; // empty subtree: not found if (value == root.data) return root; // found if (value < root.data) return search(root.left, value); // smaller: go left return search(root.right, value); // larger: go right}class TreeNode: def __init__(self, data): self.data = data self.left = None self.right = None def search(root, value): if root is None: return None # empty subtree: not found if value == root.data: return root # found if value < root.data: return search(root.left, value) # smaller: go left return search(root.right, value) # larger: go rightThe snippets focus on the operation in this lesson. The C examples need stdlib.h.
3Complexity
Each step goes one level down. At most h steps are taken, h being the height of the tree: O(log n) in a balanced tree, O(n) in the worst case.
In the recursive version one call stays open per level: O(h). The loop version uses O(1) space.
This time depends on the shape of the tree. If the tree turns into a chain, searching becomes as slow as in a linked list; you will see this in the unbalanced trees lesson.
4Common mistake
The most common mistake is putting the NULL check last:
if (value == root->data) return root; // crashes if root is NULLif (root == NULL) return NULL;If the value is not in the tree, the search ends up at a NULL child and root->data cannot be read. The empty check always comes first. The second common mistake is not returning the result of the recursive call: with search(root->left, value); alone, the node found is lost.
5Try it
Searching for 45 in the tree 50, 30, 70, 20, 40, 60, 80, which nodes are compared?
The answer is A. 45 < 50 so go left, 45 > 30 so go right, 45 > 40 so go to the right of 40. That is NULL, so 45 is not in the tree. The nodes compared are 50, 30 and 40.
Show the answer
The answer is A. 45 < 50 so go left, 45 > 30 so go right, 45 > 40 so go to the right of 40. That is NULL, so 45 is not in the tree. The nodes compared are 50, 30 and 40.
In a BST of height h, at most how many comparisons does an unsuccessful search make?
The answer is B. The path from the root to the deepest leaf has h + 1 nodes, and the search makes one comparison at each. Then it steps into a NULL child and stops.
Show the answer
The answer is B. The path from the root to the deepest leaf has h + 1 nodes, and the search makes one comparison at each. Then it steps into a NULL child and stops.
Lessons you mark show up in the curriculum. If you are signed in, they are saved to your account too.