Maximum Binary Tree - Problem
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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code