Search in a Binary Search Tree - Problem

You are given the root of a binary search tree (BST) and an integer val. Find the node in the BST that the node's value equals val and return the subtree rooted with that node. If such a node does not exist, return null.

A binary search tree is a binary tree where for every node:

  • All nodes in the left subtree have values less than the node's value
  • All nodes in the right subtree have values greater than the node's value

Input & Output

Example 1 — Basic BST Search
$ Input: root = [4,2,7,1,3], val = 2
Output: [2,1,3]
💡 Note: Start at root 4. Since 2 < 4, go left to node 2. Found target 2, return subtree rooted at 2 which contains [2,1,3].
Example 2 — Target Not Found
$ Input: root = [4,2,7,1,3], val = 5
Output: []
💡 Note: Start at root 4. Since 5 > 4, go right to node 7. Since 5 < 7, try to go left but node 7 has no left child. Target not found, return null (empty array).
Example 3 — Search Root
$ Input: root = [4,2,7,1,3], val = 4
Output: [4,2,7,1,3]
💡 Note: Start at root 4. Target equals root value, so return the entire tree rooted at 4.

Constraints

  • The number of nodes in the tree is in range [1, 5000]
  • 1 ≤ Node.val ≤ 107
  • root is a binary search tree
  • 1 ≤ val ≤ 107

Visualization

Tap to expand
Search in a Binary Search Tree INPUT Binary Search Tree: 4 2 7 1 3 Target: val = 2 (Green = subtree to return) root = [4,2,7,1,3] val = 2 ALGORITHM STEPS 1 Start at Root Compare val(2) with root(4) 2 Go Left 2 < 4, move to left child 3 Compare Again val(2) == node(2), found! 4 Return Subtree Return node and children Search Path: 4 2 4 --> 2 FOUND! Time: O(h) h = tree height FINAL RESULT Returned Subtree: 2 1 3 left right Output: [2, 1, 3] OK - Node Found! Subtree rooted at 2 Key Insight: BST property allows efficient search: at each node, compare target with current value. If smaller, go left; if larger, go right. Time complexity: O(h) where h is tree height. For balanced BST, h = log(n). Worst case (skewed tree): O(n). TutorialsPoint - Search in a Binary Search Tree | Optimal Solution
Asked in
Facebook 35 Amazon 28 Google 22 Microsoft 18
89.0K Views
Medium Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen