Problem 911
Maximum Binary Tree
Medium · 20 pts · Tree, Array, Divide and Conquer, Monotonic Stack
Problem
Build the maximum binary tree of an array of distinct integers: the root is the largest element, its left subtree is built the same way from the elements to the left of it, and its right subtree from the elements to the right. Print the tree in level order. Recursion is O(N²) in the worst case; a monotonic stack builds the same tree in O(N), since each element becomes the right child of the nearest larger element to its left or the left child of the nearest larger one to its right.
Input
The first line contains N. The second line contains N distinct integers.
Output
Print the tree as level-order tokens separated by spaces, using null for missing children and without trailing nulls.
Constraints
1 <= N <= 1000; 0 <= values <= 1000; values are distinct
Example input
6 3 2 1 6 0 5
Example output
6 3 5 null 2 0 null null 1
Explanation
For 3 2 1 6 0 5, the root is 6; its left part 3 2 1 builds 3 → 2 → 1 down the right side, and its right part 0 5 builds 5 with left child 0. In level order: 6 3 5 null 2 0 null null 1.