LintCode 126 - Max Tree


Related: LeetCode 654 - Maximum Binary Tree
Lintcode-Max Tree - LiBlog - 博客园
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.
Given [2, 5, 6, 0, 3, 1], the max tree constructed by this array is:
    6
   / \
  5   3
/   / \
2   0   1

还是用到了ordered stack。对于每个数,他的左右右节点是在他与第一个比他大的数之间,比他小的最大数,因此维护一个递减stack就可以得到。
下降stack,因为遇到上升的就自动组成一个左subtree。这个stack的思想要体会。
https://segmentfault.com/a/1190000007471356
    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;
    }
http://blog.welkinlan.com/2015/06/29/max-tree-lintcode-java/

    public TreeNode maxTree(int[] A) {
        // write your code here
        if (A == null || A.length == 0) {
            return null;
        }
        LinkedList<TreeNode> stack = new LinkedList<TreeNode>();
        for (int i = 0; i < A.length; i++) {
            TreeNode cur = new TreeNode(A[i]);
            while (!stack.isEmpty() && cur.val > stack.peek().val) {
                cur.left = stack.pop();
            }
            if (!stack.isEmpty()) {
                stack.peek().right = cur;
            }
            stack.push(cur);
        }
        TreeNode result = new TreeNode(0);
        while (!stack.isEmpty()) {
            result = stack.pop();
        }
        return result;
    }

其实这种树叫做笛卡树( Cartesian tree)。直接递归建树的话复杂度最差会退化到O(n^2)。经典建树方法,用到的是单调堆栈。我们堆栈里存放的树,只有左子树,没有有子树,且根节点最大。
(1) 如果新来一个数,比堆栈顶的树根的数小,则把这个数作为一个单独的节点压入堆栈。
(2) 否则,不断从堆栈里弹出树,新弹出的树以旧弹出的树为右子树,连接起来,直到目前堆栈顶的树根的数大于新来的数。然后,弹出的那些数,已经形成了一个新的树,这个树作为新节点的左子树,把这个新树压入堆栈。

这样的堆栈是单调的,越靠近堆栈顶的数越小
最后还要按照(2)的方法,把所有树弹出来,每个旧树作为新树的右子树


17     public TreeNode maxTree(int[] A) {
18         if (A.length==0) return null;
19 
20         Stack<TreeNode> nodeStack = new Stack<TreeNode>();
21         nodeStack.push(new TreeNode(A[0]));
22         for (int i=1;i<A.length;i++)
23             if (A[i]<=nodeStack.peek().val){
24                 TreeNode node = new TreeNode(A[i]);
25                 nodeStack.push(node);
26             } else {
27                 TreeNode n1 = nodeStack.pop();
28                 while (!nodeStack.isEmpty() && nodeStack.peek().val < A[i]){
29                     TreeNode n2 = nodeStack.pop();
30                     n2.right = n1;
31                     n1 = n2;
32                 }
33                 TreeNode node = new TreeNode(A[i]);
34                 node.left = n1;
35                 nodeStack.push(node);
36             }
37         
38 
39         TreeNode root = nodeStack.pop();
40         while (!nodeStack.isEmpty()){
41             nodeStack.peek().right = root;
42             root = nodeStack.pop();
43         }
44 
45         return root;
51     }

https://codesolutiony.wordpress.com/2015/01/28/lintcode-max-tree/
    public TreeNode maxTree(int[] A) {
        Stack<TreeNode> stack = new Stack<TreeNode>();//decreasing stack
        for (int i = 0; i < A.length; i++) {
            TreeNode newNode = new TreeNode(A[i]);
            TreeNode pre = null;
            while (!stack.isEmpty() && stack.peek().val < A[i]) {
                TreeNode cur = stack.pop();
                if (pre != null) {
                    cur.right = pre;
                }
                pre = cur;
                newNode.left = pre;
            }
            stack.push(newNode);
        }
        TreeNode preNode = null;
        while (!stack.isEmpty()) {
            TreeNode curNode = stack.pop();
            curNode.right = preNode;
            preNode = curNode;
        }
        return preNode;
    }
https://www.jianshu.com/p/e05e598c8073
  • 通过观察发现规律,对于每个node的父亲节点 = min(左边第一个比它大的,右边第一个比它大的)
  • 维护一个降序数组,可以实现对这个min的快速查找
# stack = [2], push 5 因为 5 > 2, 所以2是5的左儿子, pop 2
# stack = [], push 5
# stack = [5], push 6, 因为 6 > 5,所以5是6的左儿子, pop 5
# stack = [], push 6
# stack = [6], push 0, 因为0 < 6, stack = [6], 所以0是6的右儿子
# stack = [6, 0], push 3, 因为3 > 0, 所以0是3的左儿子, pop 0
# stack = [6], 所以3是6的右儿子, push 3
# stack = [6, 3], push 1, 因为1 < 3,所以1是3的右儿子

    def maxTree(self, A):
        # write your code here
        stack = []
        for element in A:
            node = TreeNode(element)
            while len(stack) != 0 and element > stack[-1].val:
                node.left = stack.pop()
            if len(stack) != 0:
                stack[-1].right = node
            stack.append(node)
        return stack[0]


X. Recursive
https://segmentfault.com/a/1190000007471356
    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;
    }
https://www.cnblogs.com/lishiblog/p/4187936.html
17     public TreeNode maxTree(int[] A) {
18         if (A.length==0) return null;
19 
20         TreeNode root = new TreeNode(A[0]);
21         for (int i=1;i<A.length;i++)
22             if (A[i]>root.val){
23                 TreeNode node = new TreeNode(A[i]);
24                 node.left = root;
25                 root = node;
26             } else insertNode(root,null,A[i]);
27 
28         return root;
29     }
30 
31     public void insertNode(TreeNode cur, TreeNode pre, int val){
32         if (cur==null){
33             TreeNode node = new TreeNode(val);
34             pre.right = node;
35             return;
36         }
37 
38         if (cur.val<val){
39             TreeNode node = new TreeNode(val);
40             pre.right = node;
41             node.left = cur;
42             return;
43         } else 
44             insertNode(cur.right,cur,val);
45     }

https://richdalgo.wordpress.com/2015/01/28/lintcode-max-tree/
http://dinnerwanzi.blogspot.com/2015/07/lintcode-94-binary-tree-max-sum.html
    int maxPathSum(TreeNode *root) {
        // write your code here
        if (!root)
            return 0;
        myMax=INT_MIN;
        maxHelper(root);
        return myMax;
    }
    
    int maxHelper(TreeNode* root){
        if (!root)
            return 0;
        int l=max(0, maxHelper(root->left));
        int r=max(0, maxHelper(root->right));
        myMax=max(myMax, l+r+root->val);
        return max(l,r)+root->val;
    }
    int myMax;
Read full article from Lintcode-Max Tree - LiBlog - 博客园

Labels

LeetCode (1432) GeeksforGeeks (1122) LeetCode - Review (1067) Review (882) Algorithm (668) to-do (609) Classic Algorithm (270) Google Interview (237) Classic Interview (222) Dynamic Programming (220) DP (186) Bit Algorithms (145) POJ (141) Math (137) Tree (132) LeetCode - Phone (129) EPI (122) Cracking Coding Interview (119) DFS (115) Difficult Algorithm (115) Lintcode (115) Different Solutions (110) Smart Algorithm (104) Binary Search (96) BFS (91) HackerRank (90) Binary Tree (86) Hard (79) Two Pointers (78) Stack (76) Company-Facebook (75) BST (72) Graph Algorithm (72) Time Complexity (69) Greedy Algorithm (68) Interval (63) Company - Google (62) Geometry Algorithm (61) Interview Corner (61) LeetCode - Extended (61) Union-Find (60) Trie (58) Advanced Data Structure (56) List (56) Priority Queue (53) Codility (52) ComProGuide (50) LeetCode Hard (50) Matrix (50) Bisection (48) Segment Tree (48) Sliding Window (48) USACO (46) Space Optimization (45) Company-Airbnb (41) Greedy (41) Mathematical Algorithm (41) Tree - Post-Order (41) ACM-ICPC (40) Algorithm Interview (40) Data Structure Design (40) Graph (40) Backtracking (39) Data Structure (39) Jobdu (39) Random (39) Codeforces (38) Knapsack (38) LeetCode - DP (38) Recursive Algorithm (38) String Algorithm (38) TopCoder (38) Sort (37) Introduction to Algorithms (36) Pre-Sort (36) Beauty of Programming (35) Must Known (34) Binary Search Tree (33) Follow Up (33) prismoskills (33) Palindrome (32) Permutation (31) Array (30) Google Code Jam (30) HDU (30) Array O(N) (29) Logic Thinking (29) Monotonic Stack (29) Puzzles (29) Code - Detail (27) Company-Zenefits (27) Microsoft 100 - July (27) Queue (27) Binary Indexed Trees (26) TreeMap (26) to-do-must (26) 1point3acres (25) GeeksQuiz (25) Merge Sort (25) Reverse Thinking (25) hihocoder (25) Company - LinkedIn (24) Hash (24) High Frequency (24) Summary (24) Divide and Conquer (23) Proof (23) Game Theory (22) Topological Sort (22) Lintcode - Review (21) Tree - Modification (21) Algorithm Game (20) CareerCup (20) Company - Twitter (20) DFS + Review (20) DP - Relation (20) Brain Teaser (19) DP - Tree (19) Left and Right Array (19) O(N) (19) Sweep Line (19) UVA (19) DP - Bit Masking (18) LeetCode - Thinking (18) KMP (17) LeetCode - TODO (17) Probabilities (17) Simulation (17) String Search (17) Codercareer (16) Company-Uber (16) Iterator (16) Number (16) O(1) Space (16) Shortest Path (16) itint5 (16) DFS+Cache (15) Dijkstra (15) Euclidean GCD (15) Heap (15) LeetCode - Hard (15) Majority (15) Number Theory (15) Rolling Hash (15) Tree Traversal (15) Brute Force (14) Bucket Sort (14) DP - Knapsack (14) DP - Probability (14) Difficult (14) Fast Power Algorithm (14) Pattern (14) Prefix Sum (14) TreeSet (14) Algorithm Videos (13) Amazon Interview (13) Basic Algorithm (13) Codechef (13) Combination (13) Computational Geometry (13) DP - Digit (13) LCA (13) LeetCode - DFS (13) Linked List (13) Long Increasing Sequence(LIS) (13) Math-Divisible (13) Reservoir Sampling (13) mitbbs (13) Algorithm - How To (12) Company - Microsoft (12) DP - Interval (12) DP - Multiple Relation (12) DP - Relation Optimization (12) LeetCode - Classic (12) Level Order Traversal (12) Prime (12) Pruning (12) Reconstruct Tree (12) Thinking (12) X Sum (12) AOJ (11) Bit Mask (11) Company-Snapchat (11) DP - Space Optimization (11) Dequeue (11) Graph DFS (11) MinMax (11) Miscs (11) Princeton (11) Quick Sort (11) Stack - Tree (11) 尺取法 (11) 挑战程序设计竞赛 (11) Coin Change (10) DFS+Backtracking (10) Facebook Hacker Cup (10) Fast Slow Pointers (10) HackerRank Easy (10) Interval Tree (10) Limited Range (10) Matrix - Traverse (10) Monotone Queue (10) SPOJ (10) Starting Point (10) States (10) Stock (10) Theory (10) Tutorialhorizon (10) Kadane - Extended (9) Mathblog (9) Max-Min Flow (9) Maze (9) Median (9) O(32N) (9) Quick Select (9) Stack Overflow (9) System Design (9) Tree - Conversion (9) Use XOR (9) Book Notes (8) Company-Amazon (8) DFS+BFS (8) DP - States (8) Expression (8) Longest Common Subsequence(LCS) (8) One Pass (8) Quadtrees (8) Traversal Once (8) Trie - Suffix (8) 穷竭搜索 (8) Algorithm Problem List (7) All Sub (7) Catalan Number (7) Cycle (7) DP - Cases (7) Facebook Interview (7) Fibonacci Numbers (7) Flood fill (7) Game Nim (7) Graph BFS (7) HackerRank Difficult (7) Hackerearth (7) Inversion (7) Kadane’s Algorithm (7) Manacher (7) Morris Traversal (7) Multiple Data Structures (7) Normalized Key (7) O(XN) (7) Radix Sort (7) Recursion (7) Sampling (7) Suffix Array (7) Tech-Queries (7) Tree - Serialization (7) Tree DP (7) Trie - Bit (7) 蓝桥杯 (7) Algorithm - Brain Teaser (6) BFS - Priority Queue (6) BFS - Unusual (6) Classic Data Structure Impl (6) DP - 2D (6) DP - Monotone Queue (6) DP - Unusual (6) DP-Space Optimization (6) Dutch Flag (6) How To (6) Interviewstreet (6) Knapsack - MultiplePack (6) Local MinMax (6) MST (6) Minimum Spanning Tree (6) Number - Reach (6) Parentheses (6) Pre-Sum (6) Probability (6) Programming Pearls (6) Rabin-Karp (6) Reverse (6) Scan from right (6) Schedule (6) Stream (6) Subset Sum (6) TSP (6) Xpost (6) n00tc0d3r (6) reddit (6) AI (5) Abbreviation (5) Anagram (5) Art Of Programming-July (5) Assumption (5) Bellman Ford (5) Big Data (5) Code - Solid (5) Code Kata (5) Codility-lessons (5) Coding (5) Company - WMware (5) Convex Hull (5) Crazyforcode (5) DFS - Multiple (5) DFS+DP (5) DP - Multi-Dimension (5) DP-Multiple Relation (5) Eulerian Cycle (5) Graph - Unusual (5) Graph Cycle (5) Hash Strategy (5) Immutability (5) Java (5) LogN (5) Manhattan Distance (5) Matrix Chain Multiplication (5) N Queens (5) Pre-Sort: Index (5) Quick Partition (5) Quora (5) Randomized Algorithms (5) Resources (5) Robot (5) SPFA(Shortest Path Faster Algorithm) (5) Shuffle (5) Sieve of Eratosthenes (5) Strongly Connected Components (5) Subarray Sum (5) Sudoku (5) Suffix Tree (5) Swap (5) Threaded (5) Tree - Creation (5) Warshall Floyd (5) Word Search (5) jiuzhang (5)

Popular Posts