Given the root
of a binary tree, flatten the tree into a "linked list":
TreeNode
class where the right
child pointer points to the next node in the list and the left
child pointer is always null
.
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:
[0, 2000]
.-100 <= Node.val <= 100
Follow up: Can you flatten the tree in-place (with
O(1)
extra space)?This problem requires flattening a binary tree into a linked list in a preorder traversal order. The linked list is represented by connecting nodes using the right
child pointer, with all left
child pointers set to null
.
The most efficient approach is an iterative solution that mimics preorder traversal while simultaneously modifying the tree structure. We don't need recursion or additional data structures beyond a few pointers to achieve O(1) space complexity.
Algorithm:
null
:
right
pointer to the current node's right
child.right
pointer to its left
child.left
pointer to null
.right
child.Time Complexity: O(n), where n is the number of nodes in the tree. We visit each node exactly once.
Space Complexity: O(1). We use only a few pointers for traversal and manipulation, independent of the tree size.
Here's the code implementation in several programming languages:
class Solution:
def flatten(self, root: Optional[TreeNode]) -> None:
curr = root
while curr:
if curr.left:
prev = curr.left
while prev.right:
prev = prev.right
prev.right = curr.right
curr.right = curr.left
curr.left = None
curr = curr.right
class Solution {
public void flatten(TreeNode root) {
TreeNode curr = root;
while (curr != null) {
if (curr.left != null) {
TreeNode prev = curr.left;
while (prev.right != null) {
prev = prev.right;
}
prev.right = curr.right;
curr.right = curr.left;
curr.left = null;
}
curr = curr.right;
}
}
}
class Solution {
public:
void flatten(TreeNode* root) {
TreeNode* curr = root;
while (curr != nullptr) {
if (curr->left != nullptr) {
TreeNode* prev = curr->left;
while (prev->right != nullptr) {
prev = prev->right;
}
prev->right = curr->right;
curr->right = curr->left;
curr->left = nullptr;
}
curr = curr->right;
}
}
};
var flatten = function(root) {
let curr = root;
while (curr) {
if (curr.left) {
let prev = curr.left;
while (prev.right) {
prev = prev.right;
}
prev.right = curr.right;
curr.right = curr.left;
curr.left = null;
}
curr = curr.right;
}
};
These code examples all follow the same algorithmic approach. They efficiently flatten the binary tree in-place, modifying the tree structure directly without using extra space proportional to the tree's size. The core logic remains consistent across languages, only the syntax and data structure representations change.