zoukankan      html  css  js  c++  java
  • Lintcode-Max Tree

    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 is
    
                  6
    
                /    
    
             5       3
    
           /        /   
    
         2        0     1
    
     
    
     
    
    Challenge
    O(n) time complexity
    
    Analysis:
    
    Recursion: use recursion method, in the worst case, the complexity is O(n^2).

    为啥用栈, 数组相对顺序不能变, 要找第一个比当前元素小的元素, 或大的元素, 同84. Largest Rectangle in Histogram

    public TreeNode maxTree(int[] A) {    
            // 2015-09-05  
            if (A == null || A.length == 0) {  
                return null;  
            }  
            // 栈中点的值递减  
            ArrayDeque<TreeNode> stack = new ArrayDeque<>();    
        
            // 循环len + 1次    
            for (int i = 0; i <= A.length; i++) {    
                // 假设在数组的最后加上第n+1个数,大小为正无穷    
                TreeNode curNode = (i == A.length) ? new TreeNode(Integer.MAX_VALUE)  : new TreeNode(A[i]);    
                  
                // 一次循环pop一次  
                while (!stack.isEmpty() && curNode.val > stack.peek().val) {    
                    TreeNode popNode = stack.pop();   
                    // 下面分析将popNode放在哪  
                    if (stack.isEmpty()) {    
                        curNode.left = popNode;    
                    } else {    
                        TreeNode leftPop = stack.peek();    
                        if (leftPop.val > curNode.val) {    
                            curNode.left = popNode;    
                        } else {    
                            leftPop.right = popNode;    
                        }    
                    }    
                } // while  
                stack.push(curNode);    
            }    
            // 最后push进去的是第n + 1个点    
            return stack.peek().left;    
    }  
    

     

    为了让所有的元素都加入栈  TreeNode curNode = (i == A.length) ? new TreeNode(Integer.MAX_VALUE)  : new TreeNode(A[i]);  

     同84. Largest Rectangle in Histogram 在数组后面加"0", 这些操作都是为了遍历所有的元素, 有的不需要遍历所有的元素就不需要

    其实我们整个堆栈里的元素都是从大到小排列的,而我们每次插入一个元素E的时候,目的都是为了找到那个【第一个比E小的元素】

  • 相关阅读:
    获取<input type="checkbox" >控件的checked值
    网站IIS部署及调试
    winform窗体全屏实现
    ComBox控件的使用
    在vs2005项目中,将.sln文件和.suo文件放在一个独立的文件夹内
    .NET面试题整理
    《url重写——更友好的网站url设计》
    char、varchar、nvarchar三者间的区别
    操作符"??"的用法
    Maven 学习笔记(三)
  • 原文地址:https://www.cnblogs.com/apanda009/p/7242106.html
Copyright © 2011-2022 走看看