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.

Input & Output

Example 1 — Basic Case
$ Input: nums = [3,2,1,6,0,5]
Output: [6,3,5,null,2,0,null,null,1]
💡 Note: Maximum element 6 becomes root. Left subtree built from [3,2,1] with root 3, right subtree from [0,5] with root 5.
Example 2 — Single Element
$ Input: nums = [3]
Output: [3]
💡 Note: Single element forms a tree with just the root node.
Example 3 — Sorted Array
$ Input: nums = [1,2,3,4]
Output: [4,null,3,null,2,null,1]
💡 Note: Maximum is always the rightmost element, creating a right-skewed tree.

Constraints

  • 1 ≤ nums.length ≤ 1000
  • All integers in nums are unique
  • 0 ≤ nums[i] ≤ 5000

Visualization

Tap to expand
Maximum Binary Tree Construction321605Input: [3,2,1,6,0,5]6Root (maximum)3520Left: [3,2,1]Right: [0,5]Result: Maximum Binary Tree
Understanding the Visualization
1
Input Array
Array [3,2,1,6,0,5] with no duplicates
2
Find Maximum
6 is maximum, becomes root with left=[3,2,1], right=[0,5]
3
Tree Structure
Recursively apply same rule to build complete tree
Key Takeaway
🎯 Key Insight: The largest element in any range becomes the parent of elements on its left and right
Asked in
Amazon 15 Google 12 Facebook 8 Microsoft 6
180.0K Views
Medium Frequency
~15 min Avg. Time
4.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen