Max Tree

Question: 

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

 

Analysis:

1. 递归:遍历找到最大值,然后对该最大值左半部分和右半部分分别调用递归函数。时间复杂度为O(nlogn)。
 
2. 递减stack(code见下):解题思想几乎和Largest Rectangle in Histogram一模一样,区别就在与使用的是递减栈,而不是递增栈。通过递减栈,可以找到一个值它的左边第一个比它大的数,和右边第一个比它大的数。然后比较这两个数,较小的那个就是这个值的父节点的值(好像有点绕。。比方说有一个数组[1, 5, 2, 3, 4, ...],对于数字3,它左边第一个比它大的数是5,右边第一个比它大的数是4,4比5小,所以节点3的父节点就是4,设TreeNode(4).left = TreeNode(3))。
 
Code:
 1 /**
 2  * Definition of TreeNode:
 3  * public class TreeNode {
 4  *     public int val;
 5  *     public TreeNode left, right;
 6  *     public TreeNode(int val) {
 7  *         this.val = val;
 8  *         this.left = this.right = null;
 9  *     }
10  * }
11  */
12 public class Solution {
13     /**
14      * @param A: Given an integer array with no duplicates.
15      * @return: The root of max tree.
16      */
17     public TreeNode maxTree(int[] A) {
18         int size = A.length;
19         if(A == null || size == 0) {
20             return null;
21         }
22         
23         Stack<TreeNode> stack = new Stack<TreeNode>();
24         for(int i = 0; i <= size; i++) {
25             TreeNode right = i == size ? new TreeNode(Integer.MAX_VALUE) 
26                 : new TreeNode(A[i]);
27                 
28             while(!stack.isEmpty() && right.val > stack.peek().val) {
29                 TreeNode node = stack.pop();
30                 if(stack.isEmpty()) {
31                     right.left = node;
32                 }else {
33                     TreeNode left = stack.peek();
34                     if(left.val > right.val) {
35                         right.left = node;
36                     }else {
37                         left.right = node;
38                     }
39                 }
40             }
41             
42             stack.push(right);
43         }
44         
45         return stack.peek().left;
46     }
47 }

 

Complexity:
时间复杂度是O(n)。
 
 

posted on 2016-01-22 15:44  BillZ  阅读(130)  评论(0编辑  收藏  举报

导航