LeetCode #700 Easy

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 null if no node holds val.

The tree has up to 5,000 nodes and is not promised to be balanced.

Constraints
  • 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⁷
bstbinary-searchtree
Open on LeetCode ↗
02

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.

  • val is smaller: it can only be in the left subtree.
  • val is 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.

How to spot this pattern

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.

03

Approach

Try it first

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.

1

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.

2

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.

3

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.

4

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.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
▶3 node = root
▶4 while node is not None and node.val != val:
▶5 if val < node.val:
▶6 node = node.left
▶7 else:
▶8 node = node.right
▶9 return node
val vs node2checked0ruled out042713start at the root, looking for 2
val2
node4
The pointer starts at the root, 4. Nothing has been checked yet; all 5 nodes could still hold 2.
val vs node2<4go leftchecked1ruled out1427132 is smaller than 4 → go left
node4
val2
ruled out1
2 is smaller than 4, and in a BST every smaller value sits on the left. So the right subtree of 4 (1 node) cannot hold 2 and is skipped without being looked at. Move the pointer to the left child.
val vs node2=2checked2ruled out142713found 2 → return its subtree
node2
subtree3 nodes
The node holds 2, so the loop stops and returns this node. Its children are still attached, so the green part is the subtree the problem asks for (3 nodes). 2 of 5 nodes were checked.
05

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.

▶1class Solution:
▶2 def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
▶3 if root is None or root.val == val:
▶4 return root
▶5 if val < root.val:
▶6 return self.searchBST(root.left, val)
▶7 return self.searchBST(root.right, val)
06

Common pitfalls

Dropping the result of the recursive call

✗ Wrong
if val < root.val:
    self.searchBST(root.left, val)
else:
    self.searchBST(root.right, val)
✓ Right
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

✗ Wrong
if val < node.val:
    node = node.right
✓ Right
if val < node.val:
    node = node.left

Smaller 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.

07

Edge cases

val is at the root

The loop condition is false straight away and the whole tree is returned.

A one-node tree without val, e.g. [1] with val = 2

2 is larger, so the pointer moves to the missing right child and the loop ends on null.

08

Complexity

Time
O(h)
Space
O(1)
h is the height of the tree, the length of the longest root-to-leaf path. The loop does one comparison per level and holds a single pointer. The recursive version below takes O(h) space for its call stack.
09

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.