{x}
blog image

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 TreeNode class where the right child pointer points to the next node in the list and the left child pointer is always null.
  • 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)?

Flatten Binary Tree to Linked List

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.

Approach: Iterative Preorder Traversal with In-place Modification

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:

  1. Initialization: Start with the root node.
  2. Iteration: While the current node is not null:
    • If the current node has a left child:
      • Find the rightmost node in the left subtree (this will be the predecessor node in the preorder traversal).
      • Connect the rightmost node's right pointer to the current node's right child.
      • Connect the current node's right pointer to its left child.
      • Set the current node's left pointer to null.
    • Move to the current node's 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.

Code Examples

Here's the code implementation in several programming languages:

Python

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
 

Java

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;
        }
    }
}

C++

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;
        }
    }
};

JavaScript

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.