KatInterview

105. Construct Binary Tree from Preorder and Inorder Traversal

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem requires us to reconstruct a binary tree from its preorder and inorder traversal arrays. The key to solving this lies in understanding the properties of these two traversal methods:

Solution

Construct Binary Tree from Preorder and Inorder Traversal in Python

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
        # Create a map to store indices of inorder elements for O(1) lookup.
        inorder_map = {val: i for i, val in enumerate(inorder)}
        # Keep track of the current root in the preorder list.
        self.preorder_index = 0

        # Define the recursive builder function.
        def build(in_start: int, in_end: int) -> Optional[TreeNode]:
            """Constructs a tree from inorder[in_start:in_end+1]."""
            # Base case: if the inorder subarray is empty, there is no tree.
            if in_start > in_end:
                return None
            
            # The current root value is the next element in the preorder traversal.
            root_val = preorder[self.preorder_index]
            self.preorder_index += 1
            
            # Create the root node for the current subtree.
            root = TreeNode(root_val)
            
            # Find the root's index in the inorder traversal to partition
            # left and right subtrees.
            in_root_index = inorder_map[root_val]
            
            # Recursively build the left subtree. It's crucial to build the left
            # subtree first because preorder processes roots, then left subtrees.
            root.left = build(in_start, in_root_index - 1)
            
            # Recursively build the right subtree.
            root.right = build(in_root_index + 1, in_end)
            
            return root

        # Start the recursion with the full range of the inorder array.
        return build(0, len(inorder) - 1)

Construct Binary Tree from Preorder and Inorder Traversal in 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 {
    private int preorderIndex;
    private Map<Integer, Integer> inorderMap;

    public TreeNode buildTree(int[] preorder, int[] inorder) {
        preorderIndex = 0;
        inorderMap = new HashMap<>();
        // Build a hashmap to store value -> index relations from inorder traversal for O(1) lookup.
        for (int i = 0; i < inorder.length; i++) {
            inorderMap.put(inorder[i], i);
        }

        // Start the recursive construction with the full range of the inorder array.
        return build(preorder, 0, inorder.length - 1);
    }

    private TreeNode build(int[] preorder, int inStart, int inEnd) {
        // Base case: if there are no elements to construct the subtree.
        if (inStart > inEnd) {
            return null;
        }

        // The current root's value is the next element in the preorder sequence.
        int rootVal = preorder[preorderIndex++];
        TreeNode root = new TreeNode(rootVal);

        // Find the root's index in the inorder traversal to partition
        // the left and right subtrees.
        int inRootIndex = inorderMap.get(rootVal);

        // Recursively build the left subtree.
        // The left subtree consists of elements to the left of the root in the inorder traversal.
        root.left = build(preorder, inStart, inRootIndex - 1);

        // Recursively build the right subtree.
        // The right subtree consists of elements to the right of the root in the inorder traversal.
        root.right = build(preorder, inRootIndex + 1, inEnd);

        return root;
    }
}

Construct Binary Tree from Preorder and Inorder Traversal in C++

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
private:
    // Map to store the indices of values in the inorder traversal for O(1) lookup.
    std::unordered_map<int, int> inorderMap;
    // Index to keep track of the current root in the preorder traversal.
    int preorderIndex;

    // Recursive helper function to build the tree.
    TreeNode* build(const std::vector<int>& preorder, int inStart, int inEnd) {
        // Base case: if there are no elements to construct the subtree.
        if (inStart > inEnd) {
            return nullptr;
        }

        // The current root's value is the next element in the preorder sequence.
        int rootVal = preorder[preorderIndex++];
        TreeNode* root = new TreeNode(rootVal);

        // Find the root's index in the inorder traversal to partition
        // the left and right subtrees.
        int inRootIndex = inorderMap[rootVal];

        // Recursively build the left subtree.
        // The left subtree consists of elements to the left of the root in the inorder traversal.
        root->left = build(preorder, inStart, inRootIndex - 1);

        // Recursively build the right subtree.
        // The right subtree consists of elements to the right of the root in the inorder traversal.
        root->right = build(preorder, inRootIndex + 1, inEnd);

        return root;
    }

public:
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        preorderIndex = 0;
        
        // Populate the map with value-to-index pairs from the inorder traversal.
        for (int i = 0; i < inorder.size(); ++i) {
            inorderMap[inorder[i]] = i;
        }

        // Start the recursive construction with the full range of the inorder array.
        return build(preorder, 0, inorder.size() - 1);
    }
};

Construct Binary Tree from Preorder and Inorder Traversal in TypeScript

/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function buildTree(preorder: number[], inorder: number[]): TreeNode | null {
    // Create a map for O(1) lookup of inorder indices.
    const inorderMap = new Map<number, number>();
    for (let i = 0; i < inorder.length; i++) {
        inorderMap.set(inorder[i], i);
    }
    
    // Keep track of the current root in the preorder array.
    let preorderIndex = 0;
    
    // Define the recursive builder function.
    function build(inStart: number, inEnd: number): TreeNode | null {
        // Base case: if the inorder subarray is empty.
        if (inStart > inEnd) {
            return null;
        }
        
        // The current root's value is the next in preorder.
        const rootVal = preorder[preorderIndex];
        preorderIndex++;
        
        const root = new TreeNode(rootVal);
        
        // Find root's index in inorder map. The '!' asserts that the value exists,
        // which is guaranteed by the problem constraints.
        const inRootIndex = inorderMap.get(rootVal)!;
        
        // Recursively build left and right subtrees. The left subtree must be built
        // first to correctly advance the preorderIndex through the left subtree nodes.
        root.left = build(inStart, inRootIndex - 1);
        root.right = build(inRootIndex + 1, inEnd);
        
        return root;
    }
    
    // Start the recursion with the full range of the inorder array.
    return build(0, inorder.length - 1);
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.