Binary Search Tree · Easy
LeetCode 700: Search in a Binary Search Tree — solution
Solve LeetCode 700 by walking down the BST, going left when the target is smaller and right when it is larger — O(h) time, O(1) space.
Problem in plain words
You are given the root of a binary search tree and a number val. Find the node whose value equals val and return it — the caller will see that node together with everything below it. If no node has that value, return null.
Example: in the BST with root 6, children 3 and 9, and 3 having children 1 and 4, searching for 3 returns the subtree 3 → 1, 4. Searching for 7 returns null.
Intuition
The BST property says everything in a node's left subtree is smaller and everything in its right subtree is larger. So one comparison at each node tells you which half can possibly contain val, and you can throw the other half away. This is BST search, the tree cousin of binary search.
Approach
- Start with
node = root. - While
nodeis notnullandnode.val != val: move tonode.leftifval < node.val, otherwise tonode.right. - Return
node— it is either the match ornullif you fell off the tree.
Dry run
| Step | Current node | Comparison | Move |
|---|---|---|---|
| 1 | 6 | 4 < 6 | left |
| 2 | 3 | 4 > 3 | right |
| 3 | 4 | 4 == 4 | found, return node 4 |
Java solution
class Solution {
public TreeNode searchBST(TreeNode root, int val) {
TreeNode node = root;
while (node != null && node.val != val) {
node = val < node.val ? node.left : node.right;
}
return node;
}
}Python solution
class Solution:
def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
node = root
while node and node.val != val:
node = node.left if val < node.val else node.right
return nodeComplexity
| Measure | Cost | Why |
|---|---|---|
| Time | O(h) | One node per level is visited; h is log n when balanced and n when skewed. |
| Space | O(1) | The iterative loop uses a single pointer. |
Edge cases and common mistakes
- Searching both subtrees — that works but wastes the BST property and costs O(n). Pick one side per step.
- Returning `true`/the value — the problem wants the node itself so the caller can see its subtree.
- Empty tree — the loop never runs and
nullis returned, which is correct.
›Recursive or iterative?
Both are fine. The recursive version is return val < root.val ? searchBST(root.left, val) : searchBST(root.right, val) after the base checks, but it uses O(h) stack space. The loop is just as short and uses O(1).
