← Back to Codes

2026-06-09 16:36:42

Construct Binary Tree from Preorder and Inorder Traversal in Python and Java | LeetCode #105

Learn how to solve Construct Binary Tree from Preorder and Inorder Traversal in Python and Java with beginner-friendly explanation, step-by-step dry run, custom examples, and time complexity.

Construct Binary Tree from Preorder and Inorder Traversal in Python and Java

In this tutorial, we will learn LeetCode #105: Construct Binary Tree from Preorder and Inorder Traversal in very simple language. We will understand the idea step by step, see custom examples, and write complete code in Python and Java.

What Is the Construct Binary Tree from Preorder and Inorder Traversal Problem?

This problem asks us to solve a common coding interview task using the given input. The goal is to return the correct result without using a slow brute force method.

For this problem, we will use recursion with hashmap because it gives a clean and optimized solution.

Example input:
preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]

Expected result:
Output: constructed tree

Explanation:
Preorder gives root, inorder splits left and right.

Beginner-Friendly Idea

The main idea is to avoid trying every possible answer blindly. Instead, we keep useful information while reading the input and use that information to make the next decision.

At each step, ask: “What do I already know, and how does the current value change my answer?”

Using our example:
preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]

Approach:
recursion with hashmap

We update variables step by step until we reach:
Output: constructed tree

Why Do We Use This Approach?

A direct brute force solution is usually easier to think about, but it can become slow when the input is large. The optimized approach keeps only the important state and avoids repeated work.

That is why recursion with hashmap is useful for this problem.

Step-by-Step Explanation

Let us dry run the algorithm using a custom example.

Step 1
Use this custom example.

preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]

We will solve it using recursion with hashmap.

Step 2
Look at the first important value from the example and create the variables needed by the algorithm.

current_state = based on the first value
answer = not finished yet

Step 3
Move to the next useful value and update the state.

The algorithm compares the new value with the old state.
If the new value improves the answer, we update the answer.

Step 4
Continue this process until all useful values are processed.

After processing the example, we get:

Output: constructed tree

Why?
Preorder gives root, inorder splits left and right.

Important Code Logic

The most important part is updating the algorithm state after reading each useful value. This is where the answer becomes better step by step.

Think like this:

old_state = what we knew before
current_value = value we are checking now
new_state = updated result after using current_value

For our example, the final state gives:
Output: constructed tree

Example 1

Input:
preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]

Output:
Output: constructed tree

Explanation:
Preorder gives root, inorder splits left and right.

Example 2

Input:
preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]

Output:
constructed tree

Explanation:
Preorder gives the root and inorder splits left and right parts.

Python Code

Here is the complete Python solution for LeetCode #105.

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class BinaryTreeBuilder:
    def build_tree(self, preorder, inorder):
        inorder_index = {value: index for index, value in enumerate(inorder)}
        self.preorder_index = 0

        def build(left, right):
            if left > right:
                return None

            root_value = preorder[self.preorder_index]
            self.preorder_index += 1

            root = TreeNode(root_value)
            middle = inorder_index[root_value]

            root.left = build(left, middle - 1)
            root.right = build(middle + 1, right)

            return root

        return build(0, len(inorder) - 1)


def preorder_values(root):
    if not root:
        return []
    return [root.val] + preorder_values(root.left) + preorder_values(root.right)


builder = BinaryTreeBuilder()
root = builder.build_tree([8, 4, 2, 6, 12], [2, 4, 6, 8, 12])
print(preorder_values(root))  # Output: [8, 4, 2, 6, 12]

Java Code

Here is the complete Java solution for LeetCode #105.

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode(int val) {
        this.val = val;
    }
}

class BinaryTreeBuilder {
    private int preorderIndex;
    private Map<Integer, Integer> inorderIndex;

    public TreeNode buildTree(int[] preorder, int[] inorder) {
        preorderIndex = 0;
        inorderIndex = new HashMap<>();

        for (int i = 0; i < inorder.length; i++) {
            inorderIndex.put(inorder[i], i);
        }

        return build(preorder, 0, inorder.length - 1);
    }

    private TreeNode build(int[] preorder, int left, int right) {
        if (left > right) return null;

        int rootValue = preorder[preorderIndex++];
        TreeNode root = new TreeNode(rootValue);
        int middle = inorderIndex.get(rootValue);

        root.left = build(preorder, left, middle - 1);
        root.right = build(preorder, middle + 1, right);

        return root;
    }

    private static void preorderValues(TreeNode root, List<Integer> values) {
        if (root == null) return;
        values.add(root.val);
        preorderValues(root.left, values);
        preorderValues(root.right, values);
    }

    public static void main(String[] args) {
        BinaryTreeBuilder builder = new BinaryTreeBuilder();
        TreeNode root = builder.buildTree(new int[] {8, 4, 2, 6, 12}, new int[] {2, 4, 6, 8, 12});

        List<Integer> values = new ArrayList<>();
        preorderValues(root, values);
        System.out.println(values); // [8, 4, 2, 6, 12]
    }
}

Time and Space Complexity

Time Complexity: O(n)

The time complexity depends on how many values the algorithm needs to process and whether it uses sorting, binary search, heap, or traversal.

Space Complexity: O(n)

The extra space is used for the variables or data structures needed by the optimized approach.

Final Summary

LeetCode #105: Construct Binary Tree from Preorder and Inorder Traversal becomes easier when we break it into small steps. First understand what the problem asks, then track the important state, dry run with an example, and finally write the code.