Search in a Binary Search Tree
Search in a Binary Search Tree is a easy trees & bst problem solved with the bst basics pattern.
The best approach, iterative, runs in O(h) time and O(1) space.
Below are 2 approaches in Java, from recursive up.
Problem
Given the root of a binary search tree and a value, return the subtree rooted at the node with that value, or null if it does not exist.
Examples
Example 1
- Input
root = [4, 2, 7, 1, 3], val = 2- Output
[2, 1, 3]- Why
- Return the subtree rooted at the node with value 2.
Example 2
- Input
root = [4, 2, 7, 1, 3], val = 5- Output
[]
Constraints
- The tree has
1to5000nodes; it is a valid BST.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the Java code.
| Approach | Time | Space |
|---|---|---|
| Recursive | O(h) | O(h) |
| Iterative | O(h) | O(1) |
1Recursive
O(h)O(h)If val is smaller, search left; if larger, search right; if equal, return the node.
- if root == null || root.val == val return root.
- return val < root.val ? search(left) : search(right).
class Solution {
public TreeNode searchBST(TreeNode root, int val) {
if (root == null || root.val == val) return root;
return val < root.val ? searchBST(root.left, val) : searchBST(root.right, val);
}
}2Iterative
O(h)h is O(log n) for a balanced tree, O(n) for a skewed one.O(1)Same decisions in a loop, with no call stack.
- while root != null && root.val != val: move left or right.
class Solution {
public TreeNode searchBST(TreeNode root, int val) {
while (root != null && root.val != val) root = val < root.val ? root.left : root.right;
return root;
}
}Edge cases to test
- Value not present
- Value at the root
Hints
Hint 1
At each node, the BST property tells you which one subtree could contain val.
FAQ
What is the best time complexity for Search in a Binary Search Tree?
Iterative runs in O(h) time and O(1) extra space. h is O(log n) for a balanced tree, O(n) for a skewed one.
Which pattern does Search in a Binary Search Tree use?
It is a trees & bst problem that uses the bst basics pattern. Other problems with the same pattern: Minimum element in BST, Insert into a Binary Search Tree.
Is there a brute force solution for Search in a Binary Search Tree?
Yes. Recursive takes O(h) time and O(h) space. If val is smaller, search left; if larger, search right; if equal, return the node.
Which edge cases should I test for Search in a Binary Search Tree?
Value not present; Value at the root.