Construct Binary Tree from Preorder and Inorder Traversal

Link: https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/

Constraints


    1 <= preorder.length <= 3000
    inorder.length == preorder.length
    -3000 <= preorder[i], inorder[i] <= 3000
    preorder and inorder consist of unique values.
    Each value of inorder also appears in preorder.
    preorder is guaranteed to be the preorder traversal of the tree.
    inorder is guaranteed to be the inorder traversal of the tree.

IDea

We could use a pointer i to track the element being visited in the preorder array, and use j to indicate the index of the same element in the inorder array. Construct a node using value preorder[i] and find its corresponding position j in the inorder array. Then all the inorder elements in range [0, j - 1] belongs to current node's left subtree, while all the inorder elements in range [j + 1, len - 1] belongs to its right subtree. Recursively construct the left child using the next available value in preorder (which is [i+1]) and the inorder values in range [0, j - 1]. Recursively construct the right child using the next available value in preorder and the inorder values in range [j + 1, len - 1]. The index i should be shared across all the recursive calls so that it increment by 1 at each call.

Code

class Solution {
    private int preorderIndex = 0;
    private Map<Integer, Integer> indexMap;
    
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        indexMap = new HashMap<>();
        for (int i = 0; i < inorder.length; i++) {
            indexMap.put(inorder[i], i);
        }
        
        return buildTree(preorder, inorder, 0, inorder.length - 1);
    }
    
    private TreeNode buildTree(int[] preorder, int[] inorder, int start, int end) {
        if (preorderIndex >= preorder.length || start > end) {
            return null;
        }
        
        TreeNode current = new TreeNode(preorder[preorderIndex]);
        int pivot = indexMap.get(preorder[preorderIndex++]);
        current.left = buildTree(preorder, inorder, start, pivot - 1);
        current.right = buildTree(preorder, inorder, pivot + 1, end);
        return current;
    }
}
  • Time: O(n) since we have to visit each node twice.
  • Space: O(n). The hashmap takes O(n).

Reference:

Similar problems:

posted on 2021-09-15 21:00  blackraven25  阅读(20)  评论(0编辑  收藏  举报