Search in a Binary Search Tree
Pattern: Search, insert and delete
Start at the root: if the value is smaller go left, if larger go right, until you find it or fall off the tree. Return that node (its whole subtree) or null.
Solve on LeetCodeSolve on GeeksforGeeks
The problem
Return the subtree whose root holds val, or an empty tree if no node holds it. [4, 2, 7, 1, 3] with val = 2 gives
[2, 1, 3]. Trees in the examples are written in level order, with null for a missing child, as on LeetCode.
Think first
- Where can
valbe if it is smaller than the root? - When do you stop?
- How many nodes do you visit at most?
Hints
Brute force, and why it fails
Search every node: O(n).
The key insight
The BST rule rules out a whole subtree at every step, so the search follows a single path.
Dry run
| at | 4 |
|---|
root = [4, 2, 7, 1, 3], val = 2. 2 < 4: go left.
Step 1 of 3
The plan
n = root
while n and n.val != val: n = n.left if val < n.val else n.right
return n
Complexity
- Time
O(h)- Space
O(1)
One path down.
Edge cases
- Empty tree.
- One node.
- A tree that is a chain, where h = n.
I've built my logic, show the code
Java
class Solution {
public TreeNode searchBST(TreeNode root, int val) {
TreeNode n = root;
while (n != null && n.val != val) n = val < n.val ? n.left : n.right; // smaller values live on the left
return n;
}
}C++
class Solution {
public:
TreeNode* searchBST(TreeNode* root, int val) {
TreeNode* n = root;
while (n != NULL && n->val != val) n = val < n->val ? n->left : n->right; // smaller values live on the left
return n;
}
};Python
class Solution:
def searchBST(self, root, val: int):
n = root
while n and n.val != val:
n = n.left if val < n.val else n.right # smaller values live on the left
return nCommon mistakes
- Searching both subtrees.
- Returning the value instead of the node.