码迷,mamicode.com
首页 > 其他好文 > 详细

Max Tree

时间:2016-01-22 17:37:37      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:

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)。
 
 

Max Tree

标签:

原文地址:http://www.cnblogs.com/billzhou0223/p/5151399.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!