Find a node with a given value in a binary search tree and return the subtree rooted at that node.
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
valto search for
Output Format
Output
- The node whose value is
val, ornullif 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.
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.