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 INPUT Integer Array (no duplicates) 3 i=0 2 i=1 1 i=2 6 i=3 0 i=4 5 i=5 MAX = 6 at index 3 Array Split: [3,2,1] Left Subtree [0,5] Right Subtree Input: nums = [3,2,1,6,0,5] ALGORITHM STEPS 1 Find Maximum Scan array for max value max=6 at idx=3 2 Create Root Node Root = max value (6) 3 Build Left Subtree Recurse on [3,2,1] 3-->2-->1 (chain) 4 Build Right Subtree Recurse on [0,5] 5-->0 (5 is max) Recursion Tree: 6 3 5 2 0 FINAL RESULT Maximum Binary Tree 6 3 5 2 0 1 Output (level-order): [6,3,5,null,2,0,null, null,1] Key Insight: The maximum element always becomes the root of the current subtree. This divide-and-conquer approach recursively splits the array at each max element. Time: O(n^2) worst, O(n log n) average. Optimal: Use monotonic stack for O(n) time complexity by maintaining decreasing elements. TutorialsPoint - Maximum Binary Tree | Optimal Solution (Divide and Conquer)
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