Flatten Binary Tree to Linked List

Right-root-left reverse traversal — append each node to the front of a growing chain.

Medium
Time O(n) Space O(h)
LeetCode
2 min read
tree dfs

Problem#

Flatten a binary tree into a “linked list” in place, where each node’s left is null and right points to the next preorder node.

Examples#

  • [1,2,5,3,4,null,6][1,null,2,null,3,null,4,null,5,null,6]
  • [][]

Constraints#

  • The number of nodes is in [0, 2000].

Approach#

Reverse-preorder traversal (right, left, root) with a prev pointer. At each node, set its right to prev, its left to null, and update prev to itself.

Solution#

Flatten Binary Tree to Linked List
class Solution {
public:
void flatten(TreeNode* root) {
TreeNode* prev = nullptr;
function<void(TreeNode*)> dfs = [&](TreeNode* u) {
if (!u) return;
dfs(u->right);
dfs(u->left);
u->right = prev;
u->left = nullptr;
prev = u;
};
dfs(root);
}
};

Editorial#

Walking right-left-root visits nodes in reverse preorder. Since we always prepend the current node to the already-built suffix, the chain naturally ends up in preorder. Stashing prev avoids needing a return value.

Complexity#

  • Time: O(n).
  • Space: O(h).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.