LeetCode 105 - Construct Binary Tree from Preorder and Inorder Traversal


Related: LeetCode 889 - Construct Binary Tree from Preorder and Postorder Traversal
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
For example, given
preorder = [3,9,20,15,7]
inorder = [9,3,15,20,7]
Return the following binary tree:
    3
   / \
  9  20
    /  \
   15   7

X.
https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/discuss/34541/5ms-Java-Clean-Solution-with-Caching


In this questions, most of people just loop through inorder[] to find the root. However, by caching positions of inorder[] indices using a HashMap, the run time can drop from 20ms to 5ms.
public TreeNode buildTree(int[] preorder, int[] inorder) {
    Map<Integer, Integer> inMap = new HashMap<Integer, Integer>();
    
    for(int i = 0; i < inorder.length; i++) {
        inMap.put(inorder[i], i);
    }

    TreeNode root = buildTree(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1, inMap);
    return root;
}

public TreeNode buildTree(int[] preorder, int preStart, int preEnd, int[] inorder, int inStart, int inEnd, Map<Integer, Integer> inMap) {
    if(preStart > preEnd || inStart > inEnd) return null;
    
    TreeNode root = new TreeNode(preorder[preStart]);
    int inRoot = inMap.get(root.val);
    int numsLeft = inRoot - inStart;
    
    root.left = buildTree(preorder, preStart + 1, preStart + numsLeft, inorder, inStart, inRoot - 1, inMap);
    root.right = buildTree(preorder, preStart + numsLeft + 1, preEnd, inorder, inRoot + 1, inEnd, inMap);
    
    return root;
}
Using Hashmap to cache Inorder Position
http://blog.csdn.net/linhuanmars/article/details/24389549
对于寻找根所对应的下标,我们可以先建立一个HashMap,以免后面需要进行线行搜索,这样每次递归中就只需要常量操作就可以完成对根的确定和左右子树的分割。算法最终相当于一次树的遍历,每个结点只会被访问一次,所以时间复杂度是O(n)
public TreeNode buildTree(int[] preorder, int[] inorder) {
    if(preorder==null || inorder==null)
        return null;
    HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
    for(int i=0;i<inorder.length;i++)
    {
        map.put(inorder[i],i);
    }
    return helper(preorder,0,preorder.length-1,inorder,0,inorder.length-1, map);
}
private TreeNode helper(int[] preorder, int preL, int preR, int[] inorder, int inL, int inR, HashMap<Integer, Integer> map)
{
    if(preL>preR || inL>inR)
        return null;
    TreeNode root = new TreeNode(preorder[preL]);
    int index = map.get(root.val);
    root.left = helper(preorder, preL+1, index-inL+preL, inorder, inL, index-1, map);
    root.right = helper(preorder, preL+index-inL+1, preR, inorder, index+1, inR,map);
    return root;
}


Same idea with less parameter passing. Since there is no passing by reference, I'm using a single element int array to denote the current position at preorder array. Should be quite straightforward without considering inorder array's index.
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        int[] current = {0};
        
        TreeNode root;
        Map<Integer, Integer> inMap = new HashMap<Integer, Integer>();
    
        for(int i = 0; i < inorder.length; i++) {
            inMap.put(inorder[i], i);
        }

        root = buildTree(preorder, current, 0, preorder.length - 1, inMap);
        return root;
    }
    public TreeNode buildTree(int[] preorder, int[] current, int low, int high, Map<Integer, Integer> inMap){
        if (current[0] >= preorder.length) return null;
        TreeNode root = new TreeNode(preorder[current[0]]);
        if (low > high) return null;
        else {
            current[0] += 1;
            int i = inMap.get(root.val);
            root.left = buildTree(preorder, current, low, i - 1, inMap); 
            root.right = buildTree(preorder, current, i + 1, high, inMap);
        }
        return root;
    }
}
X.
https://leetcode.com/articles/construct-binary-tree-from-preorder-and-inorder-tr/
  • Time complexity : the popleft operation is cheap \mathcal{O}(1), but search by index operation in the inorder list requires up to N operations and the construction of inorder lists for the left and right subtrees requires N - 1 operations, where N is a number of nodes in the tree. For instance, for the first call of the function, the maximum cost is N + N - 1, for the second N - 1 + N - 2, and so on and so forth. Now let's compute the number of operations for the worst case of completely unbalanced tree : N + (N - 1) + (N - 1) + (N - 2) + ... + 1, therefore the time complexity is \mathcal{O}(N^2).
  • Space complexity : \mathcal{O}(N), since we store the entire tree.
  public Pair<TreeNode, int[]> helper(int[] preorder, int[] inorder) {
    if (inorder.length == 0) {
      return new Pair(null, preorder);
    }

    // pick up the first element as a root
    int root_val = preorder[0];
    TreeNode root = new TreeNode(root_val);

    // find index of root in the inorder list
    int index = 0;
    for (; (index < inorder.length) && (inorder[index] != root_val); index++) {
    }
    preorder = Arrays.copyOfRange(preorder, 1, preorder.length);

    // root splits inorder list
    // into left and right subtrees
    int[] left_inorder = Arrays.copyOfRange(inorder, 0, index);
    int[] right_inorder = index + 1 <= inorder.length ? Arrays.copyOfRange(inorder, index + 1, inorder.length)
        : new int[0];

    // recursion
    Pair<TreeNode, int[]> p = helper(preorder, left_inorder);
    root.left = p.getKey();
    preorder = p.getValue();
    p = helper(preorder, right_inorder);
    root.right = p.getKey();
    preorder = p.getValue();

    return new Pair(root, preorder);
  }

  public TreeNode buildTree(int[] preorder, int[] inorder) {
    Pair<TreeNode, int[]> result = helper(preorder, inorder);
    return result.getKey();

  }

X. O(N^2)
https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/discuss/34538/My-Accepted-Java-Solution
public TreeNode buildTree(int[] preorder, int[] inorder) {
    return helper(0, 0, inorder.length - 1, preorder, inorder);
}

public TreeNode helper(int preStart, int inStart, int inEnd, int[] preorder, int[] inorder) {
    if (preStart > preorder.length - 1 || inStart > inEnd) {
        return null;
    }
    TreeNode root = new TreeNode(preorder[preStart]);
    int inIndex = 0; // Index of current root in inorder
    for (int i = inStart; i <= inEnd; i++) {
        if (inorder[i] == root.val) {
            inIndex = i;
        }
    }
    root.left = helper(preStart + 1, inStart, inIndex - 1, preorder, inorder);
    root.right = helper(preStart + inIndex - inStart + 1, inIndex + 1, inEnd, preorder, inorder);
    return root;
}
https://www.tianmaying.com/tutorial/LC105
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) { return work(preorder, inorder, 0, preorder.size() - 1, 0, inorder.size() - 1); } // 为了避免数组的复杂操作,这里直接用左右界和数组的引用来代表一段前序遍历和中序遍历 // 即preorder[lp, rp]代表了当前子树的前序遍历,inorder[li, ri]代表了当前子树的中序遍历 TreeNode* work(vector<int>& preorder, vector<int>& inorder, int lp, int rp, int li, int ri) { // 判断长度为0的情况 if (lp > rp) return NULL; // 设置根节点 TreeNode *root = new TreeNode(preorder[lp]); // 找到根节点在inorder中的位置 for (int k = li; k <= ri; k++) { if (preorder[lp] == inorder[k]) { // 分治处理两棵子树 root -> left = work(preorder, inorder, lp + 1, lp + (k - li), li, k - 1); root -> right = work(preorder, inorder, lp + (k - li) + 1, rp, k + 1, ri); } } // 返回这棵子树 return root; }

public TreeNode buildTree(int[] preorder, int[] inorder) {
        if (preorder == null || inorder == null ||
                preorder.length != inorder.length || preorder.length == 0)
            return null;
        return recursiveBuildTree(preorder, 0, inorder, 0, preorder.length);
    }
    private TreeNode recursiveBuildTree(int[] preorder, int preBegin, int[] inorder, int inBegin, int len) {
        assert preBegin+len <= preorder.length;
        assert inBegin+len <= inorder.length;
        if (len <= 0)       // Empty tree
            return null;
        // The beginning node in the preorder traversal is the root
        TreeNode root = new TreeNode(preorder[preBegin]);
        // Find the position of the root in the inorder traversal so as to decide the number of nodes
        // in its left subtree
        int leftTreeLen = 0;
        for(; leftTreeLen < len && inorder[inBegin+leftTreeLen] != root.val; leftTreeLen++);
        // Recursively build its left subtree and right subtree; note the change in preBegin, inBegin, and len
        TreeNode left = recursiveBuildTree(preorder, preBegin+1, inorder, inBegin, leftTreeLen);
        TreeNode right = recursiveBuildTree(preorder, preBegin+leftTreeLen+1, inorder, inBegin+leftTreeLen+1,
                len-leftTreeLen-1);
        // Link the left and right subtrees with the root
        root.left = left;
        root.right = right;
        return root;
    }
The running time T(n) satisfies the following relation:
T(n)=T(l)+T(nl1)+O(n).

When the tree is quite balanced, the time complexity is O(n) . But in case where the tree is very unbalanced (e.g. each node except the root is the right/left child of its parent), the time complexity grows up to O(n2) 
Time Complexity: O(n^2). Worst case occurs when tree is left skewed. 
http://www.geeksforgeeks.org/construct-tree-from-given-inorder-and-preorder-traversal/

X. Stack
https://blog.csdn.net/crazy1235/article/details/51559645
https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/discuss/34715/Share-my-iterative-java-solution
public TreeNode buildTree(int[] preorder, int[] inorder) {
    TreeNode root=null;
 if(preorder.length!=inorder.length)
  return root;
 
 HashMap<Integer,Integer> map=new HashMap<>();
 for(int i=0;i<inorder.length;i++)
  map.put(inorder[i], i);

 TreeNode p=root;
 Stack<TreeNode> tree=new Stack<>();
 
 for(int i=0;i<preorder.length;i++){
  int temp=map.get(preorder[i]);
  TreeNode node=new TreeNode(preorder[i]);
  if(tree.isEmpty()){
   root=node;
   tree.add(node);
   p=root;
  }
  else {
   if(temp<map.get(tree.peek().val)){
    p.left=node;
    p=p.left;
   }
   else {
    while(!tree.isEmpty()&&temp>map.get(tree.peek().val))
     p=tree.pop();
    p.right=node;
    p=p.right;
   }
  }
  tree.add(node);
 }
 return root;
    
}
https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/discuss/34712/Here-is-the-iterative-solution-in-Java
public TreeNode buildTree(int[] preorder, int[] inorder) {
        if (inorder.length==0) return null; 
        Stack<TreeNode> stack = new Stack<TreeNode>(); 
        TreeNode root = new TreeNode(Integer.MIN_VALUE);
        stack.push(root); 
        int i=0, j=0;
        TreeNode node = null; 
        TreeNode cur = root; 
        while (j<inorder.length){
            if (stack.peek().val == inorder[j]){
                node = stack.pop(); 
                j++; 
            }
            else if (node!=null){
                cur = new TreeNode(preorder[i]); 
                node.right = cur;
                node=null; 
                stack.push(cur); 
                i++; 
            }
            else {
                cur = new TreeNode(preorder[i]); 
                stack.peek().left = cur; 
                stack.push(cur);
                i++; 
            }
        }
        return root.left; 
    }
https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/discuss/34607/Deep-Understanding-on-the-Iterative-Solution
  • Let's first observe the sequence of inorder traversal.
    1) ####$---##$---0+++
    2) 0: The root node of a tree
    3) #: the left child or grandchildren of root node 0, without right child
    4) $: the left child or grandchildren of root node 0, with a right child or subtree.
    5) --- : represent right subtree of node $
    6) +++: represent right subtree of root node.
  • Let's observe the sequence of preorder traveral
    1) 0$##$###------+++
    2) The symbols are the same.
  • Maintain two pointers: ptrin, ptrpre
    1) ptrpre: pointer to preorder sequence, always points to the next node that is about to be created.
    2) ptrin: pointer to inorder sequence. When we keep pushing into stack, ptrin always points to the deepest left child of a subtree. When we keeping popping out nodes, ptrin points to nodes that has no right child, until it points to the root of the right subtree of a node that is just popped out from the stack.
  • Maintain a stack
    1) Similar with the stack in inorder traversal, it always stores the chain of left children in a subtree.
    2) When pushing stack, we are traversing the chain of left children in a subtree, and we keeping creating new node and make it as the left child of the node at stack top.
    3) When poping stack, we always pop out a node that has no right child, until we find a node that has right child (subtree).
  • Maintain a temp pointer, that always points to a node popped from stack, the last node that is popped out from the stack has right child (subtree). So the newly created node will be the right child of temp.
  • Procedures of my algorithm:
    1) Create the root node of the entire tree, record the root node for the purpose of return. Push the root node into the stack.
    2) While we has remaining node to create
(a) When we enter a new iteration, ptrin always points to the deepest left grandchild of a tree. So as long as we have not reached it, we can safely keep creating new left child (grandchild) for top node at stack. This actually creating the chain of left children for a tree, namely ###$#$0. The newly-created node will be pushed in the stack. So, next created node will be its left child.


(b) Now, after the previous step, we have reached the deepest left child of a tree. Remember inorder traveral, now we need to retreat from the deepest left child until we find the first node that has a right child or subtree. We use a temp pointer to record the node that has right child, than we create the right child for it. This is achievable, because ptrpre always points to the next node that will be created. In other word, now, the node pointed by ptrpre is the right child. This invariant is ensured by the characteristics of preorder traversal. Remember the symbol presentation: 0$##$###------+++. After we create the left children chain: 0$##$###, now the ptrpre points to the first -, which is the right child of the first node with right child (the second $).
(c) Repeat step (a) and step (c) until we create all nodes.
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        if(preorder.empty()) return NULL;
        int ppre = 0, pin = 0;
        TreeNode* root = new TreeNode(preorder[ppre++]);
        stack<TreeNode*> stk;
        stk.push(root);
        while(true) {
            while(stk.top()->val != inorder[pin]) {
                TreeNode* newnode = new TreeNode(preorder[ppre++]);
                stk.top()->left = newnode;
                stk.push(newnode);
            }
            TreeNode* node;
            while(!stk.empty() && stk.top()->val == inorder[pin]) {
                node = stk.top();
                stk.pop();
                pin++;
            }
            if(ppre == preorder.size()) break;
            TreeNode* newnode = new TreeNode(preorder[ppre++]);
            node->right = newnode;
            stk.push(newnode);
        }
        return root;
    }
http://articles.leetcode.com/2011/04/construct-binary-tree-from-inorder-and-preorder-postorder-traversal.html

http://www.cnblogs.com/grandyang/p/4296500.html
做完这道题后,大多人可能会有个疑问,怎么没有由先序和后序遍历建立二叉树呢,这是因为先序和后序遍历不能唯一的确定一个二叉树,比如下面五棵树:
    1      preorder:    1  2  3
   / \       inorder:       2  1  3
 2    3       postorder:   2  3  1

       1       preorder:     1  2  3
      /       inorder:       3  2  1
    2          postorder:   3  2  1
   /
 3

       1        preorder:    1  2  3
      /        inorder:      2  3  1
    2       postorder:  3  2  1
      \
       3

       1         preorder:    1  2  3
         \        inorder:      1  3  2
          2      postorder:  3  2  1
         /
       3

       1         preorder:    1  2  3
         \      inorder:      1  2  3
          2      postorder:  3  2  1
            \
    3

 从上面我们可以看出,对于先序遍历都为1 2 3的五棵二叉树,它们的中序遍历都不相同,而它们的后序遍历却有相同的,所以只有和中序遍历一起才能唯一的确定一棵二叉树。



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