LeetCode – Construct Binary Tree from Preorder and Inorder Traversal (Java)

Given preorder and inorder traversal of a tree, construct the binary tree.

Analysis

Consider the following example:

in-order:   4 2 5 (1) 6 7 3 8
pre-order: (1) 2 4 5  3 7 6 8

From the pre-order array, we know that first element is the root. We can find the root in in-order array. Then we can identify the left and right sub-trees of the root from in-order array.

Using the length of left sub-tree, we can identify left and right sub-trees in pre-order array. Recursively, we can build up the tree.

For this example, the constructed tree is:
construct-binary-tree-from-inorder-and-postorder-traversal

Java Solution

public TreeNode buildTree(int[] preorder, int[] inorder) {
    int preStart = 0;
    int preEnd = preorder.length-1;
    int inStart = 0;
    int inEnd = inorder.length-1;
 
    return construct(preorder, preStart, preEnd, inorder, inStart, inEnd);
}
 
public TreeNode construct(int[] preorder, int preStart, int preEnd, int[] inorder, int inStart, int inEnd){
    if(preStart>preEnd||inStart>inEnd){
        return null;
    }
 
    int val = preorder[preStart];
    TreeNode p = new TreeNode(val);
 
    //find parent element index from inorder
    int k=0;
    for(int i=0; i<inorder.length; i++){
        if(val == inorder[i]){
            k=i;
            break;
        }
    }
 
    p.left = construct(preorder, preStart+1, preStart+(k-inStart), inorder, inStart, k-1);
    p.right= construct(preorder, preStart+(k-inStart)+1, preEnd, inorder, k+1 , inEnd);
 
    return p;
}
Category >> Algorithms >> Interview  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>

  1. Sherif E. Saleh on 2015-9-25

    You may use HashMap to save time rather than looping every recursion this won’t consume much space as you already will replace the inOrder array with the hashmap.

  2. dpp on 2015-9-30

    I would rather use binary search instead of using hashmap which costing space.

  3. Ram Anvesh Reddy on 2016-6-16

    Binary search will only for in Binary Search tree not in binary tree

  4. Madhuri on 2016-9-18

    In the above code, to search for the value in in-order traversal we could use,
    while(inStart<=inEnd)
    {
    }
    instead of searching the entire in-order traversal for each val. Since we are partitioning the left half and right half in sub function calls.

  5. name on 2016-12-5


    String foo = "bar"

  6. mash on 2017-6-3

    am getting arrayindexoutofbounds with this solution

Leave a comment

*