šØ Construct Binary Tree from Preorder and Inorder Traversal (#105)
š Problem Linkā
- LeetCode - Construct Binary Tree from Preorder and Inorder Traversal
- NeetCode - Construct Binary Tree from Preorder and Inorder Traversal
š Problem Statementā
Given two integer arrays preorder and inorder where:
preorderis the preorder traversal of a binary treeinorderis 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:
- Recursive with hashmap: O(n) time, O(n) space - optimal
- 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)
}