Flatten Binary Tree to Linked List
Flatten Binary Tree to Linked List is a medium trees & bst problem solved with the tree to lists and vice-versa pattern.
The best approach, optimal (morris-style rewiring, o(1) space), runs in O(n) time and O(1) space.
Below are 2 approaches in Java, Python, C++ and JavaScript, from preorder list, then relink up.
Problem
Flatten a binary tree in place into a “linked list” that uses the right pointers, in preorder order. Every left pointer must become null.
Examples
Example 1
- Input
root = [1, 2, 5, 3, 4, null, 6]- Output
[1, null, 2, null, 3, null, 4, null, 5, null, 6]- Why
- Preorder order, linked through right pointers.
Example 2
- Input
root = []- Output
[]
Constraints
- The tree has
0to2000nodes. - In place; every left pointer must end up null.
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (2 examples, or your own). Submit also runs 9 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Preorder list, then relink | O(n) | O(n) |
| Optimal (Morris-style rewiring, O(1) space) | O(n) | O(1) |
1Preorder list, then relink
O(n)O(n)Collect nodes in preorder, then set each node's left to null and right to the next node.
- Preorder into a list; relink.
class Solution {
public void flatten(TreeNode root) {
List<TreeNode> nodes = new ArrayList<>();
pre(root, nodes);
for (int i = 0; i < nodes.size(); i++) {
nodes.get(i).left = null;
nodes.get(i).right = i + 1 < nodes.size() ? nodes.get(i + 1) : null;
}
}
private void pre(TreeNode n, List<TreeNode> out) {
if (n == null) return;
out.add(n);
pre(n.left, out);
pre(n.right, out);
}
}class Solution:
def flatten(self, root: Optional[TreeNode]) -> None:
nodes: List[TreeNode] = []
self.pre(root, nodes)
for i in range(len(nodes)):
nodes[i].left = None
nodes[i].right = nodes[i + 1] if i + 1 < len(nodes) else None
def pre(self, n: Optional[TreeNode], out: List[TreeNode]) -> None:
if n is None:
return
out.append(n)
self.pre(n.left, out)
self.pre(n.right, out)class Solution {
public:
void flatten(TreeNode* root) {
vector<TreeNode*> nodes;
pre(root, nodes);
for (size_t i = 0; i < nodes.size(); i++) {
nodes[i]->left = nullptr;
nodes[i]->right = i + 1 < nodes.size() ? nodes[i + 1] : nullptr;
}
}
private:
void pre(TreeNode* n, vector<TreeNode*>& out) {
if (n == nullptr) return;
out.push_back(n);
pre(n->left, out);
pre(n->right, out);
}
};function flatten(root) {
const nodes = [];
pre(root, nodes);
for (let i = 0; i < nodes.length; i++) {
nodes[i].left = null;
nodes[i].right = i + 1 < nodes.length ? nodes[i + 1] : null;
}
}
function pre(n, out) {
if (n === null) return;
out.push(n);
pre(n.left, out);
pre(n.right, out);
}2Optimal (Morris-style rewiring, O(1) space)
O(n)O(1)Walk down the right spine. At a node with a left child, find the rightmost node of the left subtree, hang the node's current right subtree off it, move the left subtree to the right and clear left. Continue to the right.
- cur = root.
- If cur.left != null: pred = rightmost(cur.left); pred.right = cur.right; cur.right = cur.left; cur.left = null.
- cur = cur.right.
class Solution {
public void flatten(TreeNode root) {
TreeNode cur = root;
while (cur != null) {
if (cur.left != null) {
TreeNode pred = cur.left;
while (pred.right != null) pred = pred.right;
pred.right = cur.right;
cur.right = cur.left;
cur.left = null;
}
cur = cur.right;
}
}
}class Solution:
def flatten(self, root: Optional[TreeNode]) -> None:
cur = root
while cur is not None:
if cur.left is not None:
pred = cur.left
while pred.right is not None:
pred = pred.right
pred.right = cur.right
cur.right = cur.left
cur.left = None
cur = cur.rightclass Solution {
public:
void flatten(TreeNode* root) {
TreeNode* cur = root;
while (cur != nullptr) {
if (cur->left != nullptr) {
TreeNode* pred = cur->left;
while (pred->right != nullptr) pred = pred->right;
pred->right = cur->right;
cur->right = cur->left;
cur->left = nullptr;
}
cur = cur->right;
}
}
};function flatten(root) {
let cur = root;
while (cur !== null) {
if (cur.left !== null) {
let pred = cur.left;
while (pred.right !== null) pred = pred.right;
pred.right = cur.right;
cur.right = cur.left;
cur.left = null;
}
cur = cur.right;
}
}Edge cases to test
- Empty tree
- Only left children
Hints
Hint 1
For each node with a left child, the rightmost node of that left subtree should point to the node's right subtree.
FAQ
What is the best time complexity for Flatten Binary Tree to Linked List?
Optimal (Morris-style rewiring, O(1) space) runs in O(n) time and O(1) extra space.
Which pattern does Flatten Binary Tree to Linked List use?
It is a trees & bst problem that uses the tree to lists and vice-versa pattern. Other problems with the same pattern: Binary Tree to DLL.
Is there a brute force solution for Flatten Binary Tree to Linked List?
Yes. Preorder list, then relink takes O(n) time and O(n) space. Collect nodes in preorder, then set each node's left to null and right to the next node.
Which edge cases should I test for Flatten Binary Tree to Linked List?
Empty tree; Only left children.