← DiffPush

Search in a Binary Search Tree

Baseline Binary Search Trees · Concept O(h) · O(1)

The One-Question Corridor Descent

A records archive is arranged so every corridor box answers a single question: is the file you want smaller or larger than me? Starting at the entrance box, each answer permanently discards one wing of the archive, so a handful of questions — not a shelf-by-shelf hunt — lands the clerk on the exact box, or confirms the file was never filed here.

Input: A binary search tree as a level-order array (null marks a missing child) and an integer val to locate.

Output: Return the subtree rooted at the found node, serialized as a level-order array with trailing nulls trimmed. Return an empty array if val is absent.

Constraints

Examples

Example 1

Input: {"tree":[4,2,7,1,3],"val":2}
Output: [2,1,3]
The search drops left of 4 and stops at 2, returning 2's subtree.

Example 2

Input: {"tree":[4,2,7,1,3],"val":5}
Output: []
Neither wing can hold 5, so the descent runs off the tree empty-handed.

Solve this in your browser →

Also on LeetCode ↗