Problem

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

The root is the maximum number in the array
The left subtree and right subtree are the max trees of the subarray divided by the root number.
Construct the max tree by the given array.

Example

Given [2, 5, 6, 0, 3, 1], the max tree constructed by this array is:

    6
   / \
  5   3
 /   / \
2   0   1

Note

Recursion会TLE,用Stack做吧。

Solution

Recursion

public class Solution {
    public TreeNode maxTree(int[] A) {
        if (A == null || A.length == 0) return null;
        return buildMax(A, 0, A.length-1);
    }
    public TreeNode buildMax(int[] A, int start, int end) {
        if (start > end) return null;
        int max = Integer.MIN_VALUE;
        int maxIndex = -1;
        for (int i = start; i <= end; i++) {
            if (A[i] >= max) {
                max = A[i];
                maxIndex = i;
            }
        }
        TreeNode root = new TreeNode(max);
        root.left = buildMax(A, start, maxIndex-1);
        root.right = buildMax(A, maxIndex+1, end);
        return root;
    }
}

Stack

public class Solution {
    public TreeNode maxTree(int[] A) {
        if (A == null || A.length == 0) return null;
        Stack<TreeNode> stack = new Stack<>();
        for (int i = 0; i < A.length; i++) {
            //遍历A的每个元素,创造结点node
            TreeNode node = new TreeNode(A[i]);
            //将stack中小于当前结点的结点都pop出来,存为当前结点的左子树
            while (!stack.isEmpty() && node.val >= stack.peek().val) node.left = stack.pop();
            //如果stack仍非空,剩下的结点一定大于当前结点,所以将当前结点存为stack中结点的右子树;而stack中结点本来的右子树之前已经存为当前结点的左子树了
            if (!stack.isEmpty()) stack.peek().right = node;
            //stack中存放结点的顺序为:底部为完整的max tree,从下向上是下一层孩子结点的备份,顶部是当前结点的备份
            stack.push(node);
        }
        TreeNode root = stack.pop();
        while (!stack.isEmpty()) root = stack.pop();
        return root;
    }
}

linspiration
161 声望53 粉丝