MEDIUM NC#58 Blind #67 Trees

105. Construct Binary Tree from Preorder and Inorder Traversal

📖 Problem

Given two integer arrays preorder and inorder where preorder is the preorder traversal of a binary tree and inorder is the inorder traversal of the same tree, construct and return the binary tree.

🧠 Visual Learning Aid

1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases

JS/TS Refreshers

  • Array methods (`push`, `pop`, `shift`, `slice`)
  • Object/Map/Set usage patterns
  • Function parameter and return typing
  • In-place array updates
  • Sorted array traversal
  • Boundary condition checks

Logical Thinking Concepts

  • Define invariants before coding
  • Check edge cases first (`[]`, single element, duplicates)
  • Estimate time/space before implementation
  • Apply Two Pointers reasoning pattern
  • Apply Recursion reasoning pattern

💡 Approach

  • First element in preorder is always the root
  • Find root in inorder - elements left are left subtree
  • Recursively construct left and right subtrees
  • Use hash map for O(1) root lookups in inorder
  • Time: O(n), Space: O(n)

🛠️ Hints & Pitfalls

Hints

  • First element in preorder is always the root
  • Find root in inorder - elements left are left subtree
  • Recursively construct left and right subtrees

Common Pitfalls

  • Use hash map for O(1) root lookups in inorder
  • Time: O(n), Space: O(n)

🧪 Test Cases

Hidden tests on submit: 1

Test Case 1
Not run
Input:
arrayToTree(left: number, right: number);
Expected:
Computed from hidden reference
Test Case 2
Not run
Input:
arrayToTree(left, inorderMap.get(rootValue)! - 1);
Expected:
Computed from hidden reference
Test Case 3
Not run
Input:
arrayToTree(inorderMap.get(rootValue)! + 1, right);
Expected:
Computed from hidden reference

📝 Code Editor

📚 Reference Solution

⌘K Search ⌘↩ Run ⌘S Submit