Flatten Binary Tree To Linked List

6 min read

Flatten Binary Tree to Linked List: A Complete Guide

Flatten binary tree to linked list is one of the most frequently asked tree manipulation problems in computer science interviews and algorithmic challenges. The task requires transforming a binary tree into a linked list using the same TreeNode structure, where the right child pointer acts as the next pointer in a linked list, and the left child pointer is always set to null. The resulting linked list must follow the preorder traversal order of the original tree. This problem tests your understanding of tree traversal, recursion, pointer manipulation, and in-place algorithm design It's one of those things that adds up..

Understanding the Problem

Before diving into solutions, Make sure you understand exactly what the problem demands. It matters. In practice, given the root of a binary tree, you must flatten it into a linked list in-place. The linked list should use the same TreeNode class, where the left pointer is null and the right pointer points to the next node in the list Took long enough..

Take this: consider a binary tree:

    1
   / \
  2   5
 / \   \
3   4   6

The flattened linked list should look like:

1
 \
  2
   \
    3
     \
      4
       \
        5
         \
          6

Notice that the order follows a preorder traversal: root, left subtree, right subtree And that's really what it comes down to..

Why This Problem Matters

Mastering the flatten binary tree to linked list problem offers several benefits. And it deepens your understanding of tree traversals, improves your ability to manipulate pointers without losing references, and teaches you how to work with in-place algorithms that use O(1) extra space. These skills transfer directly to real-world scenarios involving data serialization, tree-to-list conversions, and memory-efficient data structure design.

You'll probably want to bookmark this section.

Approaches to Solve the Problem

There are multiple ways to flatten a binary tree, each with different trade-offs in terms of readability, space complexity, and elegance Simple, but easy to overlook..

1. Recursive Approach (Preorder with Stack)

The most intuitive method uses recursion or an explicit stack to simulate preorder traversal. You visit nodes in root-left-right order and rewire the pointers as you go.

Steps:

  • Maintain a reference to the previously visited node.
  • For each current node, set prev.right = current and prev.left = null.
  • Update prev to the current node.
  • Recurse on the left subtree first, then the right subtree.

This approach is straightforward but uses O(h) space on the call stack, where h is the height of the tree It's one of those things that adds up..

2. Iterative Approach Using a Stack

If you want to avoid recursion, you can use an explicit stack to perform an iterative preorder traversal. Push the right child first, then the left child, so that the left child is processed first. As you pop nodes, rewire them into a chain.

3. Morris Traversal (O(1) Space)

The most elegant solution uses Morris Traversal, which achieves O(1) space complexity by temporarily modifying the tree structure. The idea is to find the predecessor of each node in the preorder sequence and use it to thread the tree.

Steps for Morris-based flattening:

  • Start at the root.
  • If the current node has a left child:
    • Find the rightmost node in the left subtree (the predecessor).
    • Set the predecessor's right pointer to the current node's right child.
    • Move the left subtree to the right.
    • Set the left child to null.
  • Move to the right child and repeat.

This method is space-efficient and demonstrates deep insight into tree structures Easy to understand, harder to ignore. Took long enough..

Step-by-Step Algorithm (Recursive)

Here is a detailed breakdown of the recursive approach:

  1. Initialize a global or non-local variable prev as null.
  2. Define a helper function that takes a node as input.
  3. If the node is null, return.
  4. Store the left and right children in temporary variables.
  5. If prev is not null, set prev.right = node and prev.left = null.
  6. Update prev to the current node.
  7. Recursively call the helper on the left child.
  8. Recursively call the helper on the right child.

This ensures that nodes are processed in preorder and rewired correctly.

Code Implementation in Python

Below is a clean implementation using the recursive approach:

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: TreeNode) -> None:
        self.prev = None
        
        def helper(node):
            if not node:
                return
            if self.prev:
                self.prev.right = node
                self.Here's the thing — prev. In real terms, left = None
            self. prev = node
            
            # Store right child because it will be overwritten
            right_child = node.right
            helper(node.

The official docs gloss over this. That's a mistake.

For the Morris traversal approach:

```python
class Solution:
    def flatten(self, root: TreeNode) -> None:
        current = root
        while current:
            if current.left:
                # Find predecessor
                predecessor = current.left
                while predecessor.right:
                    predecessor = predecessor.right
                # Rewire
                predecessor.right = current.right
                current.right = current.left
                current.left = None
            current = current.right

Complexity Analysis

Understanding the time and space complexity is crucial when evaluating solutions Worth keeping that in mind..

  • Time Complexity: All approaches visit each node exactly once, resulting in O(n) time, where n is the number of nodes.
  • Space Complexity:
    • Recursive: O(h) due to the call stack, which becomes O(n) in the worst case for a skewed tree.
    • Iterative with stack: O(n) in the worst case.
    • Morris traversal: O(1) extra space, making it the most space-efficient.

Common Pitfalls and How to Avoid Them

When working on flatten binary tree to linked list problems, watch out for these mistakes:

  • Losing the right subtree: Always store the right child before overwriting it when moving the left subtree to the right.
  • Forgetting to set left to null: The problem explicitly requires all left pointers to be null.
  • Incorrect traversal order: Ensure you process nodes in preorder, not inorder or postorder.
  • Stack overflow in recursion: For very deep trees, the recursive approach may hit the recursion limit. Consider the iterative or Morris

traversal approaches to avoid this issue.

Edge Cases to Consider

No matter which algorithm you choose, solid code must handle edge cases gracefully. For this problem, keep the following in mind:

  • Empty Tree: If the root is None, the function should simply return without doing anything. Which means all the provided implementations handle this naturally. - Single Node: A tree with only one node is already "flattened." Ensure your traversal doesn't unnecessarily attempt to rewire it.
  • Already Skewed Trees: If the tree only has right children, the algorithm should recognize that no left-to-right shifting is needed and simply traverse down the existing right pointers.

Variations and Follow-Up Questions

In technical interviews, this problem often serves as a gateway to related questions. Alternatively, they might ask you to convert the binary tree into a doubly linked list rather than a singly linked one, requiring you to manage both prev and next (or left and right) pointers simultaneously. Day to day, an interviewer might ask you to flatten the tree using an inorder or postorder traversal instead of preorder. Understanding the underlying pointer manipulation and traversal mechanics of the standard preorder flattening will make these variations much easier to tackle.

Conclusion

Flattening a binary tree to a linked list is a classic problem that tests your understanding of tree traversals and in-place pointer manipulation. While the recursive approach offers an intuitive and elegant solution, the iterative and Morris traversal methods demonstrate a deeper mastery of space optimization. By carefully managing the traversal order, safely storing overwritten pointers, and setting left children to None, you can confidently solve this problem and its many variations. Mastering these techniques not only prepares you for common interview questions but also builds a strong foundation for handling complex data structure transformations in real-world applications And that's really what it comes down to..

Just Shared

Latest Batch

Same Kind of Thing

Similar Reads

Thank you for reading about Flatten Binary Tree To Linked List. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home