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小的元素】

时间: 2024-12-10 20:35:11

Lintcode-Max Tree的相关文章

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

Lintcode: Segment Tree Query

For an integer array (index from 0 to n-1, where n is the size of this array), in the corresponding SegmentTree, each node stores an extra attribute max to denote the maximum number in the interval of the array (index from start to end). Design a que

[LintCode] Binary Tree Vertical Order Traversal

Given a binary tree, return the vertical order traversal of its nodes' values. (ie, from top to bottom, column by column). If two nodes are in the same row and column, the order should be from left to right. Have you met this question in a real inter

LintCode Binary Tree Maximum Path Sum

Given a binary tree, find the maximum path sum. The path may start and end at any node in the tree. Example Given the below binary tree: 1 / 2 3 return 6. For this problem we need to think about the problem in this way. Now we want the largest sum of

Lintcode: Segment Tree Modify

For a Maximum Segment Tree, which each node has an extra value max to store the maximum value in this node's interval. Implement a modify function with three parameter root, index and value to change the node's value with [start, end] = [index, index

[LintCode] Binary Tree Leaves Order Traversal

Given a binary tree, collect a tree's nodes as if you were doing this: Collect and remove all leaves, repeat until the tree is empty. Have you met this question in a real interview? Yes Example Given binary tree: 1 / 2 3 / \ 4 5 Returns [[4, 5, 3], [

[LintCode] Binary Tree Flipping

Given a binary tree where all the right nodes are either leaf nodes with a sibling (a left node that shares the same parent node) or empty, flip it upside down and turn it into a tree where the original right nodes turned into left leaf nodes. Return

[lintcode] Binary Tree Maximum Path Sum II

Given a binary tree, find the maximum path sum from root. The path may end at any node in the tree and contain at least one node in it. 给一棵二叉树,找出从根节点出发的路径中,和最大的一条. 这条路径可以在任何二叉树中的节点结束,但是必须包含至少一个点(也就是根了). /** * Definition of TreeNode: * public class Tr

[LintCode] Segment Tree Build II 建立线段树之二

The structure of Segment Tree is a binary tree which each node has two attributes startand end denote an segment / interval. start and end are both integers, they should be assigned in following rules: The root's start and end is given bybuild method

LintCode: Binary Tree Preorder Traversal

C++,递归 1 /** 2 * Definition of TreeNode: 3 * class TreeNode { 4 * public: 5 * int val; 6 * TreeNode *left, *right; 7 * TreeNode(int val) { 8 * this->val = val; 9 * this->left = this->right = NULL; 10 * } 11 * } 12 */ 13 14 class Solution { 15 pub