Rebuild a Binary Tree From Preorder and Inorder Crawl Logs

Last updated: November 29, 2026

Quick Overview

A crawler logged a binary tree of pages twice: once in preorder and once in inorder. Given both lists of unique page IDs, reconstruct the original tree.

Google
Coding & Algorithms
Software Engineer
Google
November 29, 2026
Software Engineer
Onsite
Coding & Algorithms
Medium

0

0

0 solved


A crawler logged a binary tree of pages twice: once in preorder and once in inorder. Given both lists of unique page IDs, reconstruct the original tree.

A Google onsite problem testing whether you see how preorder fixes the root and inorder splits the subtrees. The interviewer expects an O(n) solution with an index map rather than repeated linear searches and slicing.

What the Interviewer Expects
  • Explain that preorder's first element is the root
  • Use the inorder position of the root to size the left subtree
  • Precompute a value-to-index map for O(1) lookups
  • Avoid list slicing to keep O(n) time
  • Discuss why unique values are required
Key Topics to Cover
binary trees
tree construction
divide and conquer
hash map
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • Rebuild from inorder and postorder instead.
  • Can you rebuild from preorder and postorder alone?
  • How would you handle duplicate IDs?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Requirements

Input: preorder and inorder, same length n, unique values, consistent with one tree. Output: the root. Empty lists give None. Uniqueness matters: with duplicates, the split point in inorder is amb...

High-Level Design

Keep a pointer into preorder. The value at that pointer is the root of the current subtree. Look up its position m in inorder via a dict; everything in inorder to the left of m (within the current...


Submit Your Answer
Markdown supported