654 Maximum Binary Tree

1. Question

Given an integer array with no duplicates. A maximum tree building on this array is defined as follow:
  1. 1.
    The root is the maximum number in the array.
  2. 2.
    The left subtree is the maximum tree constructed from left part subarray divided by the maximum number.
  3. 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:
1
Input:
2
[3,2,1,6,0,5]
3
4
Output:
5
return the tree root node representing the following tree:
6
7
6
8
/ \
9
3 5
10
\ /
11
2 0
12
\
13
1
Copied!
Note:
  1. 1.
    The size of the given array will be in the range [1,1000].

2. Implementation

(1) Monotone Stack
思路:这题的要求是以数组的最大值作为树的根,然后以最大值在数组的位置一分为二,左边子数组找出最大值作为根的左儿子,右边子数组找出最大值作为右儿子,以此类推,直到数组元素都构造成树。这里可以利用单调栈找出一个数在左边比它小的最大数,和在它右边比它大的最小数,做法是维护一个单调递减的单调栈
1
/**
2
* Definition for a binary tree node.
3
* public class TreeNode {
4
* int val;
5
* TreeNode left;
6
* TreeNode right;
7
* TreeNode(int x) { val = x; }
8
* }
9
*/
10
class Solution {
11
public TreeNode constructMaximumBinaryTree(int[] nums) {
12
Stack<TreeNode> stack = new Stack<>();
13
14
for (int num : nums) {
15
TreeNode curNode = new TreeNode(num);
16
17
while (!stack.isEmpty() && stack.peek().val < num) {
18
curNode.left = stack.pop();
19
}
20
21
if (!stack.isEmpty()) {
22
stack.peek().right = curNode;
23
}
24
stack.push(curNode);
25
}
26
27
TreeNode root = null;
28
while (!stack.isEmpty()) {
29
root = stack.pop();
30
}
31
return root;
32
}
33
}
Copied!

3. Time & Space Complexity

Monotone Stack:时间复杂度O(n), 空间复杂度O(n)