Search in a BST
Search in a BST is LeetCode 700 (Easy). You get the root of a binary search tree and an integer val.
- Return the node whose value equals
val. The tree hanging under that node is the subtree the problem asks for. - Return
nullif no node holdsval.
The tree has up to 5,000 nodes and is not promised to be balanced.
- The number of nodes in the tree is in the range [1, 5000].
- 1 <= Node.val <= 10⁷
- root is a binary search tree.
- 1 <= val <= 10⁷
Intuition
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 larger. So one comparison tells you which side val must be on, and the other side can be skipped without looking at it.
valis smaller: it can only be in the left subtree.valis larger: it can only be in the right subtree.- Equal: this node is the answer, and its subtree comes with it.
The search follows a single path down from the root. If that path runs off the bottom of the tree, the value is not in it.
A sorted structure plus "find this value" means each comparison should throw away a whole part of the search space. In a binary search tree that part is a whole subtree, just as binary search on an array throws away half the array.
Approach
Before reading on, decide what a single comparison at a node tells you, and what it means when the next child you need is missing. Aim for O(h) time and no recursion.
Two ways to solve it
Move one pointer down, left or right, until it holds val or becomes null.
- No stack: constant extra space.
- Safe on chains: no recursion depth to run out of.
Return the node if it is null or holds val; otherwise return the search of the one subtree that can contain it.
- Short: three lines that mirror the definition.
- Watch out: the call stack grows to the height of the tree.
Both follow the same single path from the root, so both take O(h) time. The loop wins because it needs no call stack, which matters on a 5,000-node chain. The steps, code and demo use the loop, and the recursive code comes after the demo.
Start one pointer at the root
Set node = root. The search only ever moves this one pointer downward, so there is no stack and no recursion, and the extra space stays O(1) however tall the tree is.
Stop when the node holds val
Loop while node is not null and node.val != val. When the values match, the loop ends and you return node itself, not a copy: its left and right links still lead to the whole subtree the problem wants.
Go left or right after one comparison
If val < node.val, move to node.left; otherwise move to node.right. The ordering rules out the other child together with everything under it, so each step drops a whole subtree from the search.
A null pointer means the value is missing
If the pointer becomes null, the only place val could have been is an empty spot, so it is not in the tree. Returning node handles both outcomes at once: the matching node, or null.
Code in Python, C++ and Java
Recursion
Each call handles one node. If the node is null or holds val, return it. Otherwise return the result of searching the one subtree that could contain val; that return is what carries the found node back up to the first call.
Common pitfalls
Dropping the result of the recursive call
if val < root.val:
self.searchBST(root.left, val)
else:
self.searchBST(root.right, val)if val < root.val:
return self.searchBST(root.left, val)
return self.searchBST(root.right, val)The deeper call finds the node, but its answer is thrown away and the function falls off the end, returning None. On [4,2,7,1,3] with val = 2, the result is null instead of the subtree [2,1,3].
Going the wrong way after the comparison
if val < node.val:
node = node.rightif val < node.val:
node = node.leftSmaller values live on the left. With the sides swapped, [4,2,7,1,3] and val = 2 steps from 4 to 7, then off the tree, and returns null for a value that is there.
Edge cases
val is at the rootThe loop condition is false straight away and the whole tree is returned.
val, e.g. [1] with val = 22 is larger, so the pointer moves to the missing right child and the loop ends on null.
Complexity
Search in a BST FAQ
Why does the search take O(h) time, not O(log n)?
O(log n) holds only when the tree is balanced, and the problem does not promise that. Values inserted in increasing order build a chain where every node has only a right child; then h = n and finding the deepest value checks all 5,000 nodes.
How is this different from Floor in a BST or Ceil in a BST?
Floor and Ceil walk the same path, but the exact value may be missing, so they remember the best candidate seen on the way down. Here a missing value simply means returning null.