AlgoMaster Logo

Flatten Binary Tree to Linked List

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Preorder Traversal and Reconnection

Intuition:

The basic idea is to perform a preorder traversal of the tree and store the nodes in a list. Then, modify the pointers of each node in the list to flatten the tree into a linked list. This method is straightforward but uses extra space.

Steps:

  1. Perform a preorder traversal using a recursive function.
  2. Store each visited node in a list.
  3. Iterate through the list and adjust the left and right pointers to flatten the tree.

Code:

2. Iterative with Stack

Intuition:

This approach uses a stack to simulate the recursion stack used in preorder traversal. By iterating with a stack, we can avoid using additional space for storing nodes.

Steps:

  1. Use a stack to maintain the nodes to be processed.
  2. Push the root node onto the stack.
  3. While the stack is not empty, pop the node, process it, and push its children.
  4. Adjust the left and right pointers as you traverse each node.

Code:

3. Morris Traversal

Intuition:

Morris traversal modifies the tree structure during the traversal and is based on threaded binary trees. It allows traversal without using extra space other than a few pointers.

Steps:

  1. For each node, if it has a left child, find the rightmost node in its left subtree.
  2. Redirect the rightmost node's right pointer to the current node's right child.
  3. Move the current node to its left, then set the left to null.
  4. Continue to the right of the current node.

Code: