Search in a Binary Search Tree — Binary Search Trees
Locate a requested catalogue number in an ordered index and return that entry with everything below it, or nothing if it's absent.
Binary Search Trees · Easy
The problem
A catalogue is stored as a tree keyed by item number: every number in a left branch is smaller than the node above it and every number in a right branch is larger. Find the node whose number equals val and return it. It is displayed as that node with everything below it. If no node has that number, return an empty tree.
The story
A shop keeps its catalogue as a tree ordered by item number: in any branch, smaller numbers sit to the left and larger numbers to the right, and no number repeats. A customer asks for one item number. Find that item and hand it back together with everything stored below it, or an empty result if the shop does not stock it. The catalogue can hold up to 1500 items.
What to return
- Return the node whose number equals val. It is shown as the branch hanging from it (level-order, like any tree).
- If no node has that number, return an empty tree.
- Large hidden tests (up to 1500 nodes) run under a step budget of executed lines.
Constraints
- 1 <= number of nodes <= 1500
- -5000 <= node value <= 5000
- root is a binary search tree: all values distinct, smaller ones to the left, larger ones to the right
- -5000 <= val <= 5000
- Your code may run at most 92 counted steps on the largest case.
Example
- Input
root = [6,3,9,1,4,7,12], val = 3- Output
[3,1,4]