Skip to main content

🟨 Construct Binary Tree from Preorder and Inorder Traversal (#105)

šŸ“‹ Problem Statement​

Given two integer arrays preorder and inorder where:

  • preorder is the preorder traversal of a binary tree
  • inorder is the inorder traversal of the same tree

Construct and return the binary tree.

šŸ’” Examples​

Example 1​

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

Example 2​

Input: preorder = [-1], inorder = [-1]
Output: [-1]

šŸ”‘ Key Insights & Approach​

Core Observation:

  • Preorder: root is first element
  • Inorder: root splits left and right subtrees
  • Use this to recursively build tree

Why Recursive with HashMap?

  • O(n) time with hashmap for inorder indices
  • O(n) space for hashmap + recursion stack
  • Clean recursive structure

Approaches:

  1. Recursive with hashmap: O(n) time, O(n) space - optimal
  2. Recursive without hashmap: O(n²) time

Pattern: "Tree Construction from Traversals" using divide and conquer.

šŸ Solution: Python​

Approach: Recursive with HashMap​

Time Complexity: O(n) | Space Complexity: O(n)

from typing import List, Optional

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 hashmap for O(1) inorder lookups
inorder_map = {val: idx for idx, val in enumerate(inorder)}
self.pre_idx = 0

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

# Root is current preorder element
root_val = preorder[self.pre_idx]
root = TreeNode(root_val)
self.pre_idx += 1

# Find root in inorder to split left/right
mid = inorder_map[root_val]

# Build left and right subtrees
root.left = build(left, mid - 1)
root.right = build(mid + 1, right)

return root

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

šŸ”µ Solution: Golang​

Approach: Recursive with Map​

Time Complexity: O(n) | Space Complexity: O(n)

type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}

func buildTree(preorder []int, inorder []int) *TreeNode {
inorderMap := make(map[int]int)
for i, val := range inorder {
inorderMap[val] = i
}

preIdx := 0

var build func(left, right int) *TreeNode
build = func(left, right int) *TreeNode {
if left > right {
return nil
}

rootVal := preorder[preIdx]
root := &TreeNode{Val: rootVal}
preIdx++

mid := inorderMap[rootVal]

root.Left = build(left, mid-1)
root.Right = build(mid+1, right)

return root
}

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

šŸ“š References​