joshita / dev

Published

- 1 min read

Construct Binary Tree from Preorder and Inorder Traversal

img of Construct Binary Tree from Preorder and Inorder Traversal

Construct Binary Tree from Preorder and Inorder Traversal

Given two integer arrays preorder and inorder where preorder is the preorder traversal of a binary tree and inorder is the inorder traversal of the same tree, construct and return the binary tree.

TotalValue TotalValue

   int preOrder_Index = 0;
    private void constructABinaryTree(Node node, int[] inorder_traversal, int[] preOrder_traversal) {
        Map<Integer,Integer> mp = new HashMap<>();
        for (int i=0; i < inorder_traversal.length; i++) {
            mp.put(inorder_traversal[i], i);
        } 
     subTree(preOrder_traversal, 0, preOrder_traversal.length, mp);
    }

    private Node subTree(int[] preOrder, int left, int right, Map<Integer, Integer> mp) {

        if(left > right) {
            return null;  //cant create a tree with left being less and right being more
        }
        Node root = new Node(preOrder[preOrder_Index++], null, null);
        root.left = subTree(preOrder, 0, mp.get(root.val), mp);
        root.right = subTree(preOrder, mp.get(root.val), right, mp);

        return root;
    }