Maximum Binary Tree

Medium · Arrays & Hashing · Array · Divide and Conquer · Stack · Tree · Monotonic Stack · Binary Tree

Problem

You are given an integer array nums with no duplicate values. Build a maximum binary tree from it recursively:

An empty range gives no node. Return the root of the tree built from all of nums. The tree is shown in level order, with null for a missing child.

Examples

Input: nums = [1,4,2,5,3]
Output: [5,4,3,1,2]

5 is the root; [1,4,2] builds the left subtree rooted at 4 (with 1 on its left and 2 on its right), and [3] is the right child.

Input: nums = [2,1]
Output: [2,null,1]

2 is the root with nothing on its left, and 1 is its right child.

Input: nums = [3,2,1,6,0,5]
Output: [6,3,5,null,2,0,null,null,1]

6 splits the array into [3,2,1] and [0,5]. Each side repeats the rule.

Constraints

Approaches

Follow-up

If you only need each value’s parent or depth, you do not need nodes at all: the nearest greater values on both sides answer it. See the use cases.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…