---
# System prepended metadata

title: Construct Binary Tree from Preorder and Inorder Traversal
tags: [Medium, Tree]

---

# Construct Binary Tree from Preorder and Inorder Traversal
###### tags: `Medium` `Tree`
>question : https://leetcode.com/explore/interview/card/top-interview-questions-medium/108/trees-and-graphs/788/

>reference : [pre-, in-, post-order](https://shubo.io/iterative-binary-tree-traversal/)

>related problem : 

## Question
Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
Output: [3,9,20,null,null,15,7]
![](https://i.imgur.com/o1wb64C.png)

## My Solution
```java=
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    int preorderIndex;
    Map<Integer, Integer> inorderIndexMap;
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        preorderIndex = 0;
        inorderIndexMap = new HashMap<>();
        for(int i = 0; i < inorder.length; i++) {
            inorderIndexMap.put(inorder[i], i);
        }
        return arrayToTree(preorder, 0, preorder.length - 1);
    }
    
    private TreeNode arrayToTree(int[] preorder, int left, int right) {
        if(left > right) return null;
        
        int root_value = preorder[preorderIndex++];
        TreeNode root = new TreeNode(root_value);
        
        root.left = arrayToTree(preorder, left, inorderIndexMap.get(root_value) - 1);
        root.right = arrayToTree(preorder, inorderIndexMap.get(root_value) + 1, right);
        
        return root;
    } 
}
```
## Other Solution