LeetCode 889 - Construct Binary Tree from Preorder and Postorder Traversal


https://leetcode.com/articles/construct-binary-tree-from-preorder-and-postorder-/

Return any binary tree that matches the given preorder and postorder traversals.
Values in the traversals pre and post are distinct positive integers.

Example 1:
Input: pre = [1,2,4,5,3,6,7], post = [4,5,2,6,7,3,1]
Output: [1,2,3,4,5,6,7]

Note:
  • 1 <= pre.length == post.length <= 30
  • pre[] and post[] are both permutations of 1, 2, ..., pre.length.
  • It is guaranteed an answer exists. If there exists multiple answers, you can return any of them

https://leetcode.com/problems/construct-binary-tree-from-preorder-and-postorder-traversal/discuss/161268/C%2B%2BJavaPython-One-Pass-Real-O(N)
I see a lot of solution saying O(N), but actually not.
If it takes already O(N) time to find left part and right right, it could not be O(N).
If it is recursive solution, it should use a hashmap to reduce complexity, otherwise in most cases it has at least average O(NlogN).
Here I share my iterative solution.
We will preorder generate TreeNodes, push them to stack and postorder pop them out.
  1. Loop on pre array and construct node one by one.
  2. stack save the current path of tree.
  3. node = new TreeNode(pre[i]), if not left child, add node to the left. otherwise add it to the right.
  4. If we meet a same value in the pre and post, it means we complete the construction for current subtree. We pop it from stack
Complexity:
O(N) Time O(N) Space
    public TreeNode constructFromPrePost(int[] pre, int[] post) {
        Deque<TreeNode> s = new ArrayDeque<>();
        s.offer(new TreeNode(pre[0]));
        for (int i = 1, j = 0; i < pre.length; ++i) {
            TreeNode node = new TreeNode(pre[i]);
            while (s.getLast().val == post[j]) {
                s.pollLast(); j++;
            }
            if (s.getLast().left == null) s.getLast().left = node;
            else s.getLast().right = node;
            s.offer(node);
        }
        return s.getFirst();
    }

Actually we don't need a deque, i find using a stack easier to understand:
 public TreeNode constructFromPrePost(int[] pre, int[] post) {
        Stack<TreeNode> stack = new Stack<>();
        TreeNode root = new TreeNode(pre[0]);
        stack.push(root);
        for (int i = 1, j = 0; i < pre.length; ++i) {
            TreeNode node = new TreeNode(pre[i]);
            while (stack.peek().val == post[j]) {
                stack.pop();
                j++;
            }
            if (stack.peek().left == null) {
                stack.peek().left = node;
            } else {
                stack.peek().right = node;
            }
            stack.push(node);
        }
        return root;
    }
X. Map to cache
https://leetcode.com/problems/construct-binary-tree-from-preorder-and-postorder-traversal/discuss/161286/C%2B%2B-O(N)-recursive-solution
For two subarrays pre[a,b] and post[c,d], if we want to reconstruct a tree from them, we know that pre[a]==post[d] is the root node.
[root][......left......][...right..]  ---pre
[......left......][...right..][root]  ---post

pre[a+1] is the root node of the left subtree.
Find the index of pre[a+1] in post, then we know the left subtree should be constructed from pre[a+1, a+idx-c+1] and post[c, idx].
https://leetcode.com/problems/construct-binary-tree-from-preorder-and-postorder-traversal/discuss/161281/Clean-Java-O(N)
Map<Integer, Integer> postMap = new HashMap<>();

public TreeNode constructFromPrePost(int[] pre, int[] post) {
    int length = pre.length;
    for(int i = 0; i < post.length; i++) {
        postMap.put(post[i], i);
    }
    
    return build(0, length - 1, 0, length - 1, pre, post);
}

private TreeNode build(int preLeft, int preRight, int postLeft, int postRight, int[] pre, int[] post) {
    if(preLeft > preRight || postLeft > postRight) {
        return null;
    }
    
    TreeNode root = new TreeNode(pre[preLeft]);
    
    if(preLeft + 1 <= preRight) {
        int index = postMap.get(pre[preLeft + 1]);
        int sum = index - postLeft;
        root.left = build(preLeft + 1, preLeft + sum + 1, postLeft, index, pre, post);
        root.right = build(preLeft + sum + 2, preRight, index + 1, postRight - 1, pre, post);
    }

    return root;
}

X. https://leetcode.com/problems/construct-binary-tree-from-preorder-and-postorder-traversal/discuss/161372/Logical-Thinking-with-Code-Beats-99.89

    int preStart;

    public TreeNode constructFromPrePost(int[] pre, int[] post) {

        // corner cases to add

        preStart = 0;
        int n = post.length;
        return constructFromPrePostFrom(pre, post, 0, n - 1);
    }

    private TreeNode constructFromPrePostFrom(int[] pre, int[] post, int postStart, int postEnd) {

        if (postStart > postEnd) {
            return null;
        }

        int rootVal = post[postEnd];
        TreeNode root = new TreeNode(rootVal);
        preStart++;
        
        if (preStart == pre.length || postStart == postEnd) {
            return root;
        }
        
        int leftVal = pre[preStart];
        int lri = postStart;
        for (; lri <= postEnd; lri++) {
            if (post[lri] == leftVal) {
                break;
            }
        }
        
        root.left = constructFromPrePostFrom(pre, post, postStart, lri);
        root.right = constructFromPrePostFrom(pre, post, lri + 1, postEnd - 1);

        return root;
    }

public TreeNode constructFromPrePost(int[] pre, int[] post) {
    return buildTree(pre, post, 0, post.length - 1, new int[]{0});
}

TreeNode buildTree(int[] pre, int[] post, int left, int right, int[] index) {
    if(left > right) return null;
        
    index[0]++;
    TreeNode root = new TreeNode(post[right]);
    if(left == right) return root;
    
    int i = left;
    while(i <= right && post[i] != pre[index[0]])
        i++;
    
    root.left = buildTree(pre, post, left, i, index);
    root.right = buildTree(pre, post, i + 1, right - 1, index);
    return root;
}
https://zxi.mytechroad.com/blog/tree/leetcode-889-construct-binary-tree-from-preorder-and-postorder-traversal/
pre = [(root) (left-child) (right-child)]
post = [(left-child) (right-child) (root)]
We need to recursively find the first node in pre.left-child from post.left-child
e.g.
pre = [(1), (2,4,5), (3,6,7)]
post = [(4,5,2), (6,7,3), (1)]
First element of left-child is 2 and the length of it is 3.
root = new TreeNode(1)
root.left = build((2,4,5), (4,5,2))
root.right = build((3,6,7), (6,7,3))
Let's say the left branch has L nodes. We know the head node of that left branch is pre[1], but it also occurs last in the postorder representation of the left branch. So pre[1] = post[L-1] (because of uniqueness of the node values.) Hence, L = post.indexOf(pre[1]) + 1.
Now in our recursion step, the left branch is represnted by pre[1 : L+1] and post[0 : L], while the right branch is represented by pre[L+1 : N] and post[L : N-1].


We present a variation of Approach 1 that uses indexes to refer to the subarrays of pre and post, instead of passing copies of those subarrays. Here, (i0, i1, N) refers to pre[i0:i0+N], post[i1:i1+N].

https://leetcode.com/problems/construct-binary-tree-from-preorder-and-postorder-traversal/discuss/161312/Simple-Java-using-Stack-with-explanation
1- We know that root always comes first in PreOrder but Last in Post Order. So, if we read PreOrder list from start, and check the position of the node in Post Order list, whatever nodes come before its index in PostOrder list is sub Node of this node (this node is the parent node for sure).
2- PreOrder always start from ROOT, then LEFT, and then RIGHT. So if the current node in PreOrder list has no left node, the next node in the list is its left node for sure (please refer to the NOTE), unless the next node index in PostOrder list is higher than the current node, since we know that in PostOrder we have LEFT,RIGHT, ROOT. So what ever node comes after the current node in our PreOrder list is a sub node of the current node as long as it's index is smaller than the current node index in our PostOrder list.
Note: We assume it is the left node, as it may have a right node which comes later. Since PreOrder is Root,Left,Right, and we start reading the list from 0 index, so we do not know whether the right node exists or not. What if it has a right node and we set the first sub node as its right node.
 public TreeNode constructFromPrePost(int[] pre, int[] post) {
     if(post==null || post.length==0 || pre==null || pre.length==0) return null;
     int len = post.length; 
     HashMap<Integer,Integer> index = new HashMap<>();
     for(int i=0; i<len; i++) index.put(post[i], i); //record the indexs
     Stack<TreeNode> stack = new Stack<>();
     int i=0;
     TreeNode root = new TreeNode(pre[i++]); //the first node in our PreOrder list is always the ROOT Node
     stack.push(root);
     while(i<len){  //start reading the PreOrder list and check the indexs with PostOrder list
      TreeNode next = new TreeNode(pre[i]);      
      while(index.get(stack.peek().val)<index.get(next.val)) stack.pop(); //we remove nodes with smaller index from stack as they cannot be the next nodes' parent
      TreeNode existing = stack.pop();       
      if(existing.left==null) { //left always come first
       existing.left=next;
       stack.push(existing); stack.push(next); // we push the existing node again into the stack as it may have a right node
      }
      else {
       existing.right=next;
       stack.push(next); // we do not push the existing node anymore, as it's left and right nodes already found
      }            
      i++;
     }
     return root;
    }
When we traverse the post and visit post[i], it means all child nodes in the tree of post[i] is visited already.
Thus, we can use pre to construct the tree while use post to figure out whether the node we visit still has unvisited children.
X.
https://leetcode.com/problems/construct-binary-tree-from-preorder-and-postorder-traversal/discuss/161281/Clean-Java-O(N)


The key point is 1: preprocessing. 2: Find the correct index
Map<Integer, Integer> postMap = new HashMap<>();

public TreeNode constructFromPrePost(int[] pre, int[] post) {
    int length = pre.length;
    for(int i = 0; i < post.length; i++) {
        postMap.put(post[i], i);
    }
    
    return build(0, length - 1, 0, length - 1, pre, post);
}

private TreeNode build(int preLeft, int preRight, int postLeft, int postRight, int[] pre, int[] post) {
    if(preLeft > preRight || postLeft > postRight) {
        return null;
    }
    
    TreeNode root = new TreeNode(pre[preLeft]);
    
    if(preLeft + 1 <= preRight) {
        int index = postMap.get(pre[preLeft + 1]);
        int sum = index - postLeft;
        root.left = build(preLeft + 1, preLeft + sum + 1, postLeft, postLeft + sum, pre, post);
        root.right = build(preLeft + sum + 2, preRight, postLeft + sum + 1, postRight - 1, pre, post);
    }

    return root;
}
    public TreeNode constructFromPrePost(int[] pre, int[] post) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < post.length; i++){
            map.put(post[i], i);
        }
        return dfs(pre, 0, pre.length - 1, post, 0, post.length - 1, map);
    }
    private TreeNode dfs(int[] pre, int preStart, int preEnd, int[] post, int postStart, int postEnd, Map<Integer, Integer> map){
        if (preStart > preEnd || postStart > postEnd){
            return null;
        }
        TreeNode root = new TreeNode(pre[preStart]);
        if (preStart + 1 <= preEnd){
            int deltaIndex = map.get(pre[preStart+1]) - postStart;
            root.left = dfs(pre, preStart + 1, preStart + 1 + deltaIndex, post, postStart, postStart + deltaIndex, map);
            root.right = dfs(pre,  preStart + 1 + deltaIndex + 1, preEnd, post, postStart + deltaIndex + 1, postEnd - 1, map);
        }
        return root;
    }

X. https://leetcode.com/articles/construct-binary-tree-from-preorder-and-postorder-/
A preorder traversal is:
  • (root node) (preorder of left branch) (preorder of right branch)
While a postorder traversal is:
  • (postorder of left branch) (postorder of right branch) (root node)
For example, if the final binary tree is [1, 2, 3, 4, 5, 6, 7] (serialized), then the preorder traversal is [1] + [2, 4, 5] + [3, 6, 7], while the postorder traversal is [4, 5, 2] + [6, 7, 3] + [1].
If we knew how many nodes the left branch had, we could partition these arrays as such, and use recursion to generate each branch of the tree.
Algorithm
Let's say the left branch has L nodes. We know the head node of that left branch is pre[1], but it also occurs last in the postorder representation of the left branch. So pre[1] = post[L-1] (because of uniqueness of the node values.) Hence, L = post.indexOf(pre[1]) + 1.
Now in our recursion step, the left branch is represnted by pre[1 : L+1] and post[0 : L], while the right branch is represented by pre[L+1 : N] and post[L : N-1].
  • Time Complexity: O(N^2), where N is the number of nodes.
  • Space Complexity: O(N^2)
  public TreeNode constructFromPrePost(int[] pre, int[] post) {
    int N = pre.length;
    if (N == 0)
      return null;
    TreeNode root = new TreeNode(pre[0]);
    if (N == 1)
      return root;

    int L = 0;
    for (int i = 0; i < N; ++i)
      if (post[i] == pre[1])
        L = i + 1;

    root.left = constructFromPrePost(Arrays.copyOfRange(pre, 1, L + 1), Arrays.copyOfRange(post, 0, L));
    root.right = constructFromPrePost(Arrays.copyOfRange(pre, L + 1, N), Arrays.copyOfRange(post, L, N - 1));
    return root;

  }

We present a variation of Approach 1 that uses indexes to refer to the subarrays of pre and post, instead of passing copies of those subarrays. Here, (i0, i1, N) refers to pre[i0:i0+N], post[i1:i1+N].
  int[] pre, post;

  public TreeNode constructFromPrePost(int[] pre, int[] post) {
    this.pre = pre;
    this.post = post;
    return make(0, 0, pre.length);
  }

  public TreeNode make(int i0, int i1, int N) {
    if (N == 0)
      return null;
    TreeNode root = new TreeNode(pre[i0]);
    if (N == 1)
      return root;

    int L = 1;
    for (; L < N; ++L)
      if (post[i1 + L - 1] == pre[i0 + 1])
        break;

    root.left = make(i0 + 1, i1, L);
    root.right = make(i0 + L + 1, i1 + L, N - 1 - L);
    return root;

  }

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