You are given the root of a binary search tree (BST) and an integer val.
Locate the node whose value equals val and return the subtree rooted at that node (that is, the node itself along with everything beneath it). If no node in the tree has the value val, return null.
Example 1
Input: root = [4,2,7,1,3], val = 2
Output: [2,1,3]
The node with value 2 has children 1 and 3, so the returned subtree is [2,1,3].
Example 2
Input: root = [4,2,7,1,3], val = 5
Output: []
No node holds the value 5, so the search returns null (shown as an empty tree).
Constraints
The number of nodes in the tree is in the range [1, 5000].1 <= Node.val <= 10^7root is a binary search tree.1 <= val <= 10^7See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.
FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.
750+ engineers trained · frontend, backend, AWS & AI