Skip to content
Problem 700 · LeetCode 700(opens in a new tab)

Search in a Binary Search Tree

EasyBinary search trees

A binary search tree starts at root, and you are looking for the number val. In such a tree every value in a node's left subtree is smaller than the node's value, every value in its right subtree is larger, and no value appears twice.

Find the node whose value is val and return it; the tree hanging below it comes along as the answer. If no node holds val, return null.

Example 1

Input:  root = [20,10,30,5,15,25,40,null,null,12,18], val = 15
Output: [15,12,18]
Why:    the node 15 is returned with its children
2 more examples and the constraints

Example 2

Input:  root = [9,4,16,2,6], val = 11
Output: []
Why:    no node holds 11, so the answer is null

Example 3

Input:  root = [7], val = 7
Output: [7]
Why:    the root itself is the match

Constraints

  • 1 ≤ number of nodes ≤ 5,000
  • 1 ≤ node values ≤ 10,000,000, all different
  • 1 ≤ val ≤ 10,000,000
  • root is a valid binary search tree

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Check every nodeO(n)
  2. Walk down one pathO(h)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeNodes checked for a miss in a balanced tree of 5,000 nodesVerdict
Check every nodeO(n)
Passes; ignores the order
Walk down one pathO(h)
Best; about 13 nodes, not 5,000

n = number of nodes, h = height of the tree. On a chain h = n, and the two cost the same.

Edge cases to test

  • Value missing. The walk falls off a leaf and returns null, shown as [].
  • The root matches. The loop never runs and the whole tree is the answer.
  • A chain. If values were inserted in sorted order the tree is one long path, so h = n; the loop handles it without deep recursion.
  • Outside the range. A val smaller than every node walks down the far left edge and stops at null.

Common mistakes

  • Searching both subtrees, which turns an O(h) lookup into O(n).
  • Returning a new node or a copy instead of the node in the tree.
  • Going right when val < node.val, which mixes up which side holds the smaller values.

How to talk through it

  1. 1Clarify. Are the values distinct? Should I return the node itself, and null when it is missing?
  2. 2Name the slow way. Any tree search that visits every node works, in O(n).
  3. 3Use the order. Smaller goes left, larger goes right, so each comparison discards a whole subtree.
  4. 4State the cost. O(h) time: about log n when balanced, n for a chain. The loop uses O(1) space.
  5. 5Test out loud. Run a hit at the root, a hit at a leaf, and a value that is not there.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?