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. 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

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

/**
 * 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:时间复杂度O(n), 空间复杂度O(n)

Last updated