Flatten a Binary Tree Into a Preorder Linked List In Place

Last updated: November 29, 2026

Quick Overview

Rewire a binary tree in place so that it becomes a right-leaning chain following preorder, with every left pointer set to None. Use O(1) extra space.

Google
Coding & Algorithms
Software Engineer
Google
November 29, 2026
Software Engineer
Technical Screen
Coding & Algorithms
Medium

0

0

0 solved


Rewire a binary tree in place so that it becomes a right-leaning chain following preorder, with every left pointer set to None. Use O(1) extra space.

A Google technical screen question that checks pointer manipulation. The easy answer uses a list or recursion; the interviewer then asks for the O(1) space version based on finding each node's preorder predecessor, which is the Morris idea.

What the Interviewer Expects
  • Give a simple version using recursion or a stack first
  • Find the rightmost node of the left subtree as the splice point
  • Rewire pointers so the left subtree moves to the right
  • Achieve O(n) time and O(1) extra space
  • Verify the result is a valid preorder chain
Key Topics to Cover
binary trees
pointer manipulation
Morris traversal
preorder
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
  • Flatten into inorder order instead.
  • Restore the original tree afterwards; what extra information do you need?
  • Flatten a multilevel doubly linked list with the same technique.
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: binary tree root. Mutate it so that following right pointers visits nodes in the original preorder and every left is None. Return nothing. Extra space should be O(1) beyond the tree itself....

High-Level Design

Walk down the right spine with a cursor. At each node that has a left child, find the rightmost node of that left subtree: in preorder, it is the last node visited before the current node's right subt...


Submit Your Answer
Markdown supported