# 654 Maximum Binary Tree

## 654. [Maximum Binary Tree](https://leetcode.com/problems/maximum-binary-tree/description/)

## 1. Question

Given an integer array with no duplicates. A maximum tree building on this array is defined as follow:

1. The root is the maximum number in the array.
2. The left subtree is the maximum tree constructed from left part subarray divided by the maximum number.
3. The right subtree is the maximum tree constructed from right part subarray divided by the maximum number.

Construct the maximum tree by the given array and output the root node of this tree.

**Example 1:**

```
Input:
 [3,2,1,6,0,5]

Output:
 return the tree root node representing the following tree:

      6
    /   \
   3     5
    \    / 
     2  0   
       \
        1
```

**Note:**

1. The size of the given array will be in the range \[1,1000].

## 2. Implementation

**(1) Monotone Stack**

思路：这题的要求是以数组的最大值作为树的根，然后以最大值在数组的位置一分为二，左边子数组找出最大值作为根的左儿子，右边子数组找出最大值作为右儿子，以此类推，直到数组元素都构造成树。这里可以利用单调栈找出一个数在左边**比它小的最大数**，和在它右边**比它大的最小数**，做法是维护一个单调递减的单调栈

```java
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode constructMaximumBinaryTree(int[] nums) {
        Stack<TreeNode> stack = new Stack<>();

        for (int num : nums) {
            TreeNode curNode = new TreeNode(num);

            while (!stack.isEmpty() && stack.peek().val < num) {
                curNode.left = stack.pop();
            }

            if (!stack.isEmpty()) {
                stack.peek().right = curNode;
            }
            stack.push(curNode);
        }

        TreeNode root = null;
        while (!stack.isEmpty()) {
            root = stack.pop();
        }
        return root;
    }
}
```

## 3. Time & Space Complexity

**Monotone Stack：**&#x65F6;间复杂度O(n), 空间复杂度O(n)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://protegejj.gitbook.io/algorithm-practice/leetcode/stack/654-maximum-binary-tree.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
