Maximum Binary Tree (LeetCode 654): Solution and Explanation
Given an array of distinct integers, build the tree whose root is the largest value, whose left subtree is built the same way from the values left of it, and whose right subtree from the values right of it.
Intuition
The definition suggests recursion: find the maximum, split, recurse. That is correct, but on a sorted array every split peels off one element and the total work is O(n^2).
Look at the finished tree instead. Reading it inorder gives back the array, and every node's parent is larger than it. In fact a value's parent is the smaller of its nearest larger value on the left and its nearest larger value on the right.
Nearest larger values are what a monotonic stack finds. Scan left to right keeping nodes with decreasing values. When a bigger value arrives, the smaller nodes it pops all belong under it, and the node left on top (if any) is bigger, so the new value hangs to its right.
Approach: Monotonic decreasing stack
- Keep a stack of nodes whose values decrease from bottom to top.
- For each value x, create a node and pop every stack node smaller than x, remembering the last one popped.
- The last node popped is the largest value between the bigger node on the stack and x, so it becomes node.left.
- If the stack is not empty, its top is the nearest bigger value on the left: set top.right = node. A later, larger value may replace this link.
- Push the node. When the scan ends, the bottom of the stack is the maximum and therefore the root.
Step-by-step example
nums = [3,2,1,6,0,5]
- Push 3. Then 2 is smaller: 3.right = 2, push. Then 1: 2.right = 1, push. Stack [3,2,1].
- 6 pops 1, 2 and 3. The last popped, 3, becomes 6.left; the chain 3 -> 2 -> 1 comes along. Stack [6].
- 0: 6.right = 0, push. Stack [6,0].
- 5 pops 0, which becomes 5.left. 6 is still on the stack, so 6.right = 5, replacing 0. Stack [6,5].
- The bottom of the stack, 6, is the root: [6,3,5,null,2,0,null,null,1].
Code: Python, Java, C++
1class Solution:
2 def constructMaximumBinaryTree(self, nums: List[int]) -> Optional[TreeNode]:
3 stack = []
4 for x in nums:
5 node = TreeNode(x)
6 last = None
7 while stack and stack[-1].val < x:
8 last = stack.pop()
9 node.left = last
10 if stack:
11 stack[-1].right = node
12 stack.append(node)
13 return stack[0]1class Solution {
2 public TreeNode constructMaximumBinaryTree(int[] nums) {
3 Deque<TreeNode> stack = new ArrayDeque<>();
4 for (int x : nums) {
5 TreeNode node = new TreeNode(x);
6 TreeNode last = null;
7 while (!stack.isEmpty() && stack.peek().val < x) {
8 last = stack.pop();
9 }
10 node.left = last;
11 if (!stack.isEmpty()) {
12 stack.peek().right = node;
13 }
14 stack.push(node);
15 }
16 return stack.peekLast();
17 }
18}1class Solution {
2public:
3 TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
4 vector<TreeNode*> stk;
5 for (int x : nums) {
6 TreeNode* node = new TreeNode(x);
7 TreeNode* last = nullptr;
8 while (!stk.empty() && stk.back()->val < x) {
9 last = stk.back();
10 stk.pop_back();
11 }
12 node->left = last;
13 if (!stk.empty()) {
14 stk.back()->right = node;
15 }
16 stk.push_back(node);
17 }
18 return stk.front();
19 }
20};Time and space complexity
O(n)
Each node is pushed once and popped at most once, so all the while-loop iterations together are bounded by n.
O(n)
The stack can hold all n nodes when the array is decreasing.
Other approaches
Recursive max and split (time O(n^2) worst, O(n log n) average, space O(n))
Follow the definition literally: scan the range for its maximum, then recurse on both sides. Simple and close to the statement, but quadratic on sorted input.
Recursion with a sparse table for range maximum (time O(n log n) preprocessing, space O(n log n))
Precompute range-maximum queries so each split finds its maximum in O(1). Linear-time recursion, but more code than the stack.
Common mistakes
- Attaching the first popped node instead of the last one as the left child. The first popped is the smallest; the last popped is the largest and is the root of everything popped.
- Forgetting to overwrite top.right. The right link set earlier is temporary; a later larger value takes over that slot and takes the old right child as its left.
- Returning the top of the stack instead of the bottom. The bottom holds the maximum.
- Using a non-strict comparison is harmless here only because values are distinct.
Frequently asked questions
Why does the last popped node become the left child?
Popped nodes are smaller than x and lie to its left. Among them the last popped is the largest, and the earlier popped ones already hang below it, so it is the root of the whole block left of x.
Is this tree a Cartesian tree?
Yes. A maximum binary tree is a max Cartesian tree of the array: heap-ordered by value and inorder equal to the array. The stack method is the standard linear Cartesian tree construction.
When is the simple recursion good enough?
With at most 1000 values, even the O(n^2) recursion passes. The stack version matters when the array is large or nearly sorted.