Flatten Binary Tree to Linked List
Medium
Topics
Given the root of a binary tree, flatten it into a linked list in place. The list must use the same TreeNode type, where right is the next node and left is always null.
The order must be the tree’s pre-order traversal. Return the values of the flattened list from head to tail.
Example 1
left null and right pointing at the next — not a fresh list of copies.null marks a missing child.Input: root = [1,2,5,3,4,null,6] Output: [1,2,3,4,5,6]
Example 2
Input: root = [] Output: []
Example 3
Input: root = [0] Output: [0]
Constraints
- 0 <= number of nodes <= 2000
- -100 <= Node.val <= 100
Editorial — intuition, approach, complexity and pitfalls
Intuition
Pre-order visits a node, then everything in its left subtree, then everything in its right. So in the flattened list a node is followed by its whole left subtree, and the right subtree is pushed out to the very end of that run.
Rewiring one node is therefore local: put the left subtree on the right, and reattach the old right subtree to the tail of what was just moved. Doing that at every node, working down, flattens the tree without any extra storage.
Approach
- Start at the root and walk down the right spine.
- If the current node has no left child, step right and continue.
- Otherwise find the rightmost node of its left subtree — that is where the current right subtree has to be reattached, since it comes last in pre-order.
- Hang the current right subtree off that rightmost node, move the left subtree across to
right, and clearleft. Then step right into the subtree just moved.
Walkthrough
root = [1,2,5,3,4,null,6]
1 1
/ \ \
2 5 -> 2
/ \ \ \
3 4 6 3
\
4
\
5
\
6
At node 1: left subtree is 2-3-4, its rightmost node is 4.
Hang 5 off 4, move 2 to the right of 1, clear 1.left.Complexity
- Time — O(n): each edge is walked a constant number of times; every node is moved at most once.
- Space — O(1): only a couple of pointers. A recursive version instead uses the call stack.
Common Pitfalls
- Overwriting
node.rightbefore saving it loses the whole right subtree. - Forgetting to set
leftto null leaves a tree that happens to have the right order but is not a list. - The reattachment point is the rightmost node of the left subtree, not the left subtree’s root or its deepest node.
Full Solution — all languages
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def flatten(self, root):
out = []
def preorder(node):
if not node:
return
out.append(node.val)
preorder(node.left)
preorder(node.right)
preorder(root)
return outimport java.util.*;
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int v) {
val = v;
}
}
class Solution {
public int[] flatten(TreeNode root) {
List<Integer> out = new ArrayList<>();
preorder(root, out);
int[] res = new int[out.size()];
for (int i = 0; i < res.length; i++) res[i] = out.get(i);
return res;
}
private void preorder(TreeNode node, List<Integer> out) {
if (node == null) return;
out.add(node.val);
preorder(node.left, out);
preorder(node.right, out);
}
}#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
TreeNode *left, *right;
TreeNode(int v): val(v), left(nullptr), right(nullptr) {
}
};
class Solution {
public: vector<int> flatten(TreeNode* root) {
vector<int> out;
function<void(TreeNode*)> preorder = [&](TreeNode* node) {
if (!node) return;
out.push_back(node->val);
preorder(node->left);
preorder(node->right);
};
preorder(root);
return out;
}
};/**
* Tree node shape: { val, left, right }
* @param {TreeNode} root
* @return {number[]}
*/ var flatten = function(root) {
const out = [];
const preorder = (node) => {
if (!node) return;
out.push(node.val);
preorder(node.left);
preorder(node.right);
};
preorder(root);
return out;
};