Flatten Binary Tree to Linked List
Problem Statement
You are given the root of a binary tree. Change the tree in place so it becomes a flat chain made of the same nodes.
Use right to link each node to the next one, and set every left to null. The chain must follow the preorder of the original tree: the node first, then its whole left subtree, then its whole right subtree.
The root of a binary tree. The tree can be empty.
Nothing is returned. The tree itself is changed into the flat chain.
The preorder is 1, 2, 3, 4, 5, 6. Each right points to the next value, and every left is null.
There is nothing to flatten.
A single node is already a flat chain.
- β’ 0 β€ number of nodes β€ 2000
- β’ β100 β€ Node.val β€ 100
- β’ Follow-up: can you flatten the tree in place using O(1) extra space?
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Collect the nodes in preorder into a vector, then point each right at the next one
Walk right, then left, then the node, and point each right at the node built before it
Walk down the chain; for each left subtree, hang the right subtree at its rightmost node and move it right
Walk the tree in preorder and store every node pointer in a vector. Then go down the vector: set each node's left to null and its right to the next node in the vector. Nothing is relinked during the walk, so the old links are still there when we need them.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Tree DFS translate into production architectures and low-level memory mechanics.
Foundations: Object-Oriented Principles in C++23
Class invariants, pure virtual interfaces, and RAII smart pointers.
Food Delivery System (Zomato Architecture)
Real-world machine coding application of algorithms and design patterns.
Pointers vs References Deep Dive
Pointer arithmetic and memory layout under the hood.
Virtual Method Table (vtable) & Memory Layout
Polymorphism, vptr overhead, and multiple inheritance in memory.