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
Understanding the Visualization
1
Input
BST tree and target value to search for
2
Search
Navigate using BST property to find target node
3
Output
Return subtree rooted at found node or null if not found
Key Takeaway
🎯 Key Insight: BST property allows us to navigate directly to the target without visiting unnecessary nodes
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code