Description
Flatten Binary Tree to Linked List
Given the root of a binary tree, flatten the tree into a “linked list”:
- The “linked list” should use the same
TreeNodeclass where therightchild pointer points to the next node in the list and theleftchild pointer is alwaysnull. - The “linked list” should be in the same order as a pre-order traversal of the binary tree.
Example 1:

Input: root = [1,2,5,3,4,null,6]
Output: [1,null,2,null,3,null,4,null,5,null,6]
Example 2:
Input: root = []
Output: []
Example 3:
Input: root = [0]
Output: [0]
Constraints:
- The number of nodes in the tree is in the range
[0, 2000]. -100 <= Node.val <= 100
Follow up: Can you flatten the tree in-place (with O(1) extra space)?
Approach 1: Reverse Postorder DFS ( Time, Space)
Intuition
Standard Preorder traversal is . If we traverse the tree in Reverse Preorder (), we visit nodes in the exact opposite order of the final linked list:
- Maintain a global
prevpointer initialized tonull. - Recursively traverse the
rightsubtree first, then theleftsubtree. - For the current node, set
node.right = prevandnode.left = null. - Update
prev = node.
class Solution {
private TreeNode prev = null;
public void flatten(TreeNode root) {
if (root == null) return;
// Reverse Preorder: Right -> Left -> Root
flatten(root.right);
flatten(root.left);
root.right = prev;
root.left = null;
prev = root;
}
}
Complexity
- Time Complexity: — Visits every node in the binary tree exactly once.
- Space Complexity: — Recursion call stack requires space proportional to tree height ( for balanced, for skewed).
Approach 2: Morris-Style Traversal ( Time, Space)
Intuition
Achieves auxiliary space by rewiring pointers in-place without recursion or a stack:
- Iterate through nodes using pointer
curr. - If
currhas aleftchild:- Find the rightmost node (
pred) incurr’s left subtree. - Attach
pred.righttocurr.right(reserving the rest of the tree). - Shift
curr’s left subtree to its right side (curr.right = curr.left), and setcurr.left = null.
- Find the rightmost node (
- Advance
curr = curr.rightand repeat untilcurr == null.
class Solution {
public void flatten(TreeNode root) {
TreeNode curr = root;
while (curr != null) {
if (curr.left != null) {
// Find rightmost node of left subtree
TreeNode pred = curr.left;
while (pred.right != null) {
pred = pred.right;
}
// Connect rightmost node to original right child
pred.right = curr.right;
// Splice left subtree into right pointer
curr.right = curr.left;
curr.left = null;
}
// Advance to next node on right branch
curr = curr.right;
}
}
}
Complexity
- Time Complexity: — Each node is visited at most twice (once by
currand once while findingpred). - Space Complexity: — Modifies tree in-place without stack or queue memory.
Easy Memory Rule
“Reverse Preorder () using
prevpointer OR Morris: Attachcurr.rightto rightmost node ofcurr.left, then shift left subtree to right!”