Skip to main content
Back to problems
Leetcode
Easy
Trees
Binary Search
Recursion
Search in a Binary Search Tree

Find a node with a given value in a binary search tree and return the subtree rooted at that node.

Acceptance 100%
Problem Statement

Given the root of a binary search tree (BST) and an integer value val, search the tree for a node whose value equals val.

If such a node exists, return the subtree rooted at that node. If no such node exists, return null.

Because the tree is a BST, you can use the ordering property at each step to decide whether to go left or right.

Input Format

Input

  • A binary search tree root root
  • An integer val to search for

Output Format

Output

  • The node whose value is val, or null if it does not exist

Constraints

  • The tree satisfies the Binary Search Tree property.
  • Node values are unique in the tree.
  • You may assume the tree is valid and finite.
Examples
Sample cases returned by the problem API.

Example 1

Input

root = [4,2,7,1,3], val = 2

Output

[2,1,3]

Explanation

The value 2 exists in the tree, so return the subtree rooted at node 2.

Example 2

Input

root = [4,2,7,1,3], val = 5

Output

null

Explanation

No node in the tree has value 5.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.