Unlike the other problems in this set, this tree is not built by inserting keys one at a time — it is built directly from a sorted array.
You are given n distinct integers, already sorted in strictly ascending order. Build a binary search tree from them using the standard recursive middle-element method: build(lo, hi) returns an empty tree when lo > hi; otherwise let mid = (lo + hi) // 2 (integer floor division), create a node holding a[mid], and attach build(lo, mid - 1) as its left child and build(mid + 1, hi) as its right child. The whole tree is build(0, n - 1).
Report the height of the resulting tree, where the height of an empty tree is 0 and the height of a tree with a single node is 1 (i.e., height is the number of nodes on the longest root-to-leaf path).
Line 1: an integer n.
Line 2: n space-separated integers a_1 < a_2 < ... < a_n, already sorted ascending.
A single integer: the height of the tree built by the method above.
Example 1
Input
1 5
Expected
1
Explanation
A single value builds a tree with just one node, so the height is 1.
Example 2
Input
7 1 2 3 4 5 6 7
Expected
3
Explanation
With 7 sorted values, the middle-split construction picks index 3 (value 4) as the root, whose children are values 2 and 6, whose children are the remaining leaves — a tree of height 3.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →