LeetCode ยท #700

Search in a Binary Search Tree Solution

Exploit the BST ordering property so each comparison removes an entire subtree from consideration.

01
Section One ยท Problem

Problem Statement

๐Ÿท๏ธ

Difficulty

Easy

๐Ÿ”—

LeetCode

Problem #700

๐Ÿ—๏ธ

Pattern

BST search โ€” one-path elimination

Given the root of a BST and an integer val, return the subtree rooted at the node with that value. If it does not exist, return null.

Example
Input: root = [4,2,7,1,3], val = 2 Output: subtree rooted at 2
02
Section Two ยท Approach 1

DFS on Both Sides โ€” O(n)

Treat the BST like a general binary tree and recursively search both left and right subtrees.

Problem: This ignores the BST property. If the target is smaller than the current node, the entire right subtree is guaranteed to be useless.
03
Section Three ยท Approach 2

BST-Guided Search โ€” O(h)

At every node, compare val with node.val:

  • If equal, return this node.
  • If smaller, continue only in the left subtree.
  • If larger, continue only in the right subtree.
๐Ÿ’ก Mental model: It is binary search on a linked structure. Each comparison tells you which half of the remaining values can be thrown away immediately.
Iterative is ideal here: The logic is just a while-loop over one root-to-leaf path, so recursion adds no real benefit.
04
Section Four ยท Trace

Visual Walkthrough

Search for 2 in [4,2,7,1,3]
Compare target with current node and keep only one side. 2 < 4 โ†’ go left 2 == 2 โ†’ found target The right subtree of 4 was never visited. Answer: node 2 โœ“
05
Section Five ยท Implementation

Code โ€” Java & Python

Java โ€” iterative
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; } }
Python โ€” iterative
class Solution: def searchBST(self, root, val: int): while root and root.val != val: root = root.left if val < root.val else root.right return root
06
Section Six ยท Analysis

Complexity Analysis

ApproachTimeSpace
General DFSO(n)O(h)
BST-guided searchO(h)O(1)
07
Section Seven ยท Edge Cases

Edge Cases & Pitfalls

CaseWhy it matters
Target is rootReturn immediately after first comparison.
Target missingEventually hit null and return null.
Skewed BSTHeight becomes O(n), so search also becomes O(n).
โš  Common Mistake: Recursing into both subtrees as if this were a general binary tree. BST ordering is the whole reason the search is fast.

โ† Back to BST problems