Maximum Binary Tree

You are given an integer array `nums` with no duplicates. A **maximum binary tree** can be built recursively from `nums` using the following algorithm: 1. Create a root node whose value is the maximum value in `nums`. 2. Recursively build the left subtree on the **subarray prefix** to the **left** of the maximum value. 3. Recursively build the right subtree on the **subarray suffix** to the **right** of the maximum value. Return the **maximum binary tree** built from `nums`.

30:00

Maximum Binary Tree
medium
Free written solution
Topics
Companies

You are given an integer array nums with no duplicates. A maximum binary tree can be built recursively from nums using the following algorithm:

  1. Create a root node whose value is the maximum value in nums.
  2. Recursively build the left subtree on the subarray prefix to the left of the maximum value.
  3. Recursively build the right subtree on the subarray suffix to the right of the maximum value.

Return the maximum binary tree built from nums.

Example 1:
Input: {"nums":[3,2,1,6,0,5]}
Output: [6,3,5,null,2,0,null,null,1]
Constraints:
  • 1≤nums.length≤10001 \leq \text{nums.length} \leq 1000

  • 0≤nums[i]≤10000 \leq \text{nums}[i] \leq 1000

  • All integers in nums are unique.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"nums":[3,2,1,6,0,5]}

Scan left to right with a stack whose values only decrease from bottom to top. Each node on it is still waiting for a possible right child.

nums (tree x = array index)321605

stack, bottom to top (strictly decreasing; each waits for a right child)

empty

n = 6

current value
on the stack
popped (goes under x)
link set this step
Variables
VariableValue
x-
stack[]
DepthFunction Call
Stack empty
0/24