Flatten a Binary Tree into Linked List

Last Updated : 28 Aug, 2026

Given the root of a binary tree, flatten the tree into a Linked list using Preorder.

  • The linked list should use the same Node 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 nodes should be in the same order as a preorder traversal of the binary tree.

Examples: 

Input: root[] = [1, 2, 5, 3, 4, N, 6]

2683

Output: [1, 2, 3, 4, 5, 6]
Explanation: After flattening, the tree looks like:
1
\
2
\
3
\
4
\
5
\
6
Here, left of each node points to NULL and right contains the next node in preorder. The inorder traversal of this flattened tree is 1 2 3 4 5 6.

Input: root[] = [1, 3, 4, N, N, 2, N, N, 5]

2684

Output: [1, 3, 4, 2, 5]
Explanation: After flattening, the tree looks like:
1
\
3
\
4
\
2
\
5
Here, left of each node points to NULL and right contains the next node in preorder. The inorder traversal of this flattened tree is 1 3 4 2 5.

Try It Yourself
redirect icon

[Naive Approach] Preorder + Find Tail - O(n^2) Time and O(h) Space

  1. Flatten the left subtree.
  2. Flatten the right subtree.
  3. Move the flattened left subtree to the right.
  4. Attach the flattened right subtree after it.
Flatten Binary Tree Example
C++
#include <bits/stdc++.h>
using namespace std;

/* Structure of a Binary Tree Node */
class Node
{
public:
    int data;
    Node *left;
    Node *right;

    Node(int val)
    {
        data = val;
        left = nullptr;
        right = nullptr;
    }
};

// Returns the last node of the flattened subtree.
Node *flattenTree(Node *root)
{
    // Base case
    if (root == nullptr)
        return nullptr;

    // Flatten left and right subtrees.
    Node *leftTail = flattenTree(root->left);
    Node *rightTail = flattenTree(root->right);

    // If left subtree exists, place it between
    // root and the original right subtree.
    if (root->left!= nullptr)
    {
        Node *tempRight = root->right;

        root->right = root->left;
        root->left = nullptr;

        // Attach original right subtree after
        // the flattened left subtree.
        leftTail->right = tempRight;
    }

    // Return the last node of the flattened subtree.
    if (rightTail!= nullptr)
        return rightTail;

    if (leftTail!= nullptr)
        return leftTail;

    return root;
}

void flatten(Node *root)
{
    flattenTree(root);
}

void printFlattenedTree(Node *root)
{
    while (root!= nullptr)
    {
        cout << root->data << " ";
        root = root->right;
    }

    cout << endl;
}

int main()
{
    /*
            1
           / \
          2   5
         / \   \
        3   4   6
    */

    Node *root = new Node(1);

    root->left = new Node(2);
    root->right = new Node(5);

    root->left->left = new Node(3);
    root->left->right = new Node(4);

    root->right->right = new Node(6);

    flatten(root);

    cout << "Flattened Binary Tree: ";
    printFlattenedTree(root);

    return 0;
}
Java
import java.util.LinkedList;
import java.util.Queue;

/* Structure of a Binary Tree Node */
class Node {
    public int data;
    public Node left;
    public Node right;

    public Node(int val) {
        data = val;
        left = null;
        right = null;
    }
}

public class Main {
    
    // Returns the last node of the flattened subtree.
    private static Node flattenTree(Node root) {
        
        // Base case
        if (root == null)
            return null;

        // Flatten left and right subtrees.
        Node leftTail = flattenTree(root.left);
        Node rightTail = flattenTree(root.right);

        // If left subtree exists, place it between
        // root and the original right subtree.
        if (root.left!= null) {
            Node tempRight = root.right;

            root.right = root.left;
            root.left = null;

            // Attach original right subtree after
            // the flattened left subtree.
            leftTail.right = tempRight;
        }

        // Return the last node of the flattened subtree.
        if (rightTail!= null)
            return rightTail;

        if (leftTail!= null)
            return leftTail;

        return root;
    }

    public static void flatten(Node root) {
        flattenTree(root);
    }

    public static void printFlattenedTree(Node root) {
        while (root!= null) {
            System.out.print(root.data + " ");
            root = root.right;
        }

        System.out.println();
    }

    public static void main(String[] args) {
        /*
                1
               / \
              2   5
             / \   \
            3   4   6
        */

        Node root = new Node(1);

        root.left = new Node(2);
        root.right = new Node(5);

        root.left.left = new Node(3);
        root.left.right = new Node(4);

        root.right.right = new Node(6);

        flatten(root);

        System.out.print("Flattened Binary Tree: ");
        printFlattenedTree(root);
    }
}
Python
class Node:
    def __init__(self, val):
        self.data = val
        self.left = None
        self.right = None

# Returns the last node of the flattened subtree.
def flattenTree(root):
    
    # Base case
    if root is None:
        return None

    # Flatten left and right subtrees.
    leftTail = flattenTree(root.left)
    rightTail = flattenTree(root.right)

    # If left subtree exists, place it between
    # root and the original right subtree.
    if root.left is not None:
        tempRight = root.right

        root.right = root.left
        root.left = None

        # Attach original right subtree after
        # the flattened left subtree.
        leftTail.right = tempRight

    # Return the last node of the flattened subtree.
    if rightTail is not None:
        return rightTail

    if leftTail is not None:
        return leftTail

    return root

def flatten(root):
    flattenTree(root)

def printFlattenedTree(root):
    while root is not None:
        print(root.data, end=' ')
        root = root.right

    print('')

root = Node(1)

root.left = Node(2)
root.right = Node(5)

root.left.left = Node(3)
root.left.right = Node(4)

root.right.right = Node(6)

flatten(root)

print('Flattened Binary Tree:')
printFlattenedTree(root)
C#
using System;

// Structure of a Binary Tree Node
public class Node {
    public int data;
    public Node left;
    public Node right;

    public Node(int val) {
        data = val;
        left = null;
        right = null;
    }
}

public class MainClass {

    // Returns the last node of the flattened subtree.
    private static Node flattenTree(Node root) {

        // Base case
        if (root == null)
            return null;

        // Flatten left and right subtrees.
        Node leftTail = flattenTree(root.left);
        Node rightTail = flattenTree(root.right);

        // If left subtree exists, place it between
        // root and the original right subtree.
        if (root.left!= null) {
            Node tempRight = root.right;

            root.right = root.left;
            root.left = null;

            // Attach original right subtree after
            // the flattened left subtree.
            leftTail.right = tempRight;
        }

        // Return the last node of the flattened subtree.
        if (rightTail!= null)
            return rightTail;

        if (leftTail!= null)
            return leftTail;

        return root;
    }

    public static void flatten(Node root) {
        flattenTree(root);
    }

    public static void printFlattenedTree(Node root) {
        while (root!= null) {
            Console.Write(root.data + " ");
            root = root.right;
        }

        Console.WriteLine();
    }

    public static void Main(string[] args) {
        /*
                1
               / \
              2   5
             / \   \
            3   4   6
        */

        Node root = new Node(1);

        root.left = new Node(2);
        root.right = new Node(5);

        root.left.left = new Node(3);
        root.left.right = new Node(4);

        root.right.right = new Node(6);

        flatten(root);

        Console.Write("Flattened Binary Tree: ");
        printFlattenedTree(root);
    }
}
JavaScript
/* Structure of a Binary Tree Node */
class Node {
    constructor(val) {
        this.key = val;
        this.left = null;
        this.right = null;
    }
}

// Returns the last node of the flattened subtree.
function flattenTree(root) {
    
    // Base case
    if (root === null)
        return null;

    // Flatten left and right subtrees.
    let leftTail = flattenTree(root.left);
    let rightTail = flattenTree(root.right);

    // If left subtree exists, place it between
    // root and the original right subtree.
    if (root.left!== null) {
        let tempRight = root.right;

        root.right = root.left;
        root.left = null;

        // Attach original right subtree after
        // the flattened left subtree.
        leftTail.right = tempRight;
    }

    // Return the last node of the flattened subtree.
    if (rightTail!== null)
        return rightTail;

    if (leftTail!== null)
        return leftTail;

    return root;
}

function flatten(root) {
    flattenTree(root);
}

function printFlattenedTree(root) {
    while (root!== null) {
        console.log(root.key + " ");
        root = root.right;
    }

    console.log("");
}

let root = new Node(1);

root.left = new Node(2);
root.right = new Node(5);

root.left.left = new Node(3);
root.left.right = new Node(4);

root.right.right = new Node(6);

flatten(root);

console.log("Flattened Binary Tree:");
printFlattenedTree(root);

Output
1 2 3 4 5 6 

[Better Approach] Reverse Preorder - O(n) Time and O(h) Space

The idea is to process the tree in reverse preorder: Right -> Left -> Root, so that when we process a node, its next node in the required preorder list is already available in prev.

We then connect root-> right to prev and set root-> left = null, gradually building the flattened list in Root -> Left -> Right order.

  • If root is null, return the previously processed node prev.
  • Recursively process the right subtree first and update prev.
  • Recursively process the left subtree and update prev.
  • Set root->right = prev and make root->left = null.
  • Update prev = root and return it.
  • This reverse preorder processing builds the flattened tree in preorder: Root -> Left -> Right.
C++
#include <bits/stdc++.h>
using namespace std;

/* Structure of a Binary Tree Node */
class Node
{
  public:
    int data;
    Node *left;
    Node *right;

    Node(int val)
    {
        data = val;
        left = nullptr;
        right = nullptr;
    }
};

Node *flattenTree(Node *root, Node *prev)
{
    // Base case: empty tree
    if (root == nullptr)
        return prev;

    // Process right subtree first
    prev = flattenTree(root->right, prev);

    // Process left subtree
    prev = flattenTree(root->left, prev);

    // Connect current node to previously processed node
    root->right = prev;

    // Left pointer must always be NULL
    root->left = nullptr;

    // Update prev to current node
    prev = root;

    return prev;
}

void flatten(Node *root)
{
    // Initialize previous node as NULL
    Node *prev = nullptr;

    flattenTree(root, prev);
}

void printFlattenedTree(Node *root)
{
    while (root!= nullptr)
    {
        cout << root->data << " ";
        root = root->right;
    }

    cout << endl;
}

int main()
{
    /*
            1
           / \
          2   5
         / \   \
        3   4   6
    */

    Node *root = new Node(1);
    root->left = new Node(2);
    root->right = new Node(5);

    root->left->left = new Node(3);
    root->left->right = new Node(4);

    root->right->right = new Node(6);

    flatten(root);
    printFlattenedTree(root);

    return 0;
}
Java
/* Structure of a Binary Tree Node */
class Node {
    int data;
    Node left;
    Node right;

    Node(int val)
    {
        data = val;
        left = null;
        right = null;
    }
}

class GFG {
    static Node flattenTree(Node root, Node prev)
    {
        // Base case: empty tree
        if (root == null)
            return prev;

        // Process right subtree first
        prev = flattenTree(root.right, prev);

        // Process left subtree
        prev = flattenTree(root.left, prev);

        // Connect current node to previously processed node
        root.right = prev;

        // Left pointer must always be NULL
        root.left = null;

        // Update prev to current node
        prev = root;

        return prev;
    }

    static void flatten(Node root)
    {
        // Initialize previous node as NULL
        Node prev = null;

        prev = flattenTree(root, prev);
    }

    static void printFlattenedTree(Node root)
    {
        while (root!= null) {
            System.out.print(root.data + " ");
            root = root.right;
        }

        System.out.println();
    }

    public static void main(String[] args)
    {
        /*
                1
               / \
              2   5
             / \   \
            3   4   6
        */

        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(5);

        root.left.left = new Node(3);
        root.left.right = new Node(4);

        root.right.right = new Node(6);

        flatten(root);
        printFlattenedTree(root);
    }
}
Python
# Structure of a Binary Tree Node
class Node:
    def __init__(self, val):
        self.data = val
        self.left = None
        self.right = None

def flattenTree(root, prev):
    
    # Base case: empty tree
    if root is None:
        return prev

    # Process right subtree first
    prev = flattenTree(root.right, prev)

    # Process left subtree
    prev = flattenTree(root.left, prev)

    # Connect current node to previously processed node
    root.right = prev

    # Left pointer must always be NULL
    root.left = None

    # Update prev to current node
    prev = root

    return prev

def flatten(root):
    
    # Initialize previous node as NULL
    prev = None
    flattenTree(root, prev)

def printFlattenedTree(root):
    while root is not None:
        print(root.data, end=" ")
        root = root.right
    print()

# Driver Code
if __name__ == "__main__":
    """            1           / \          2   5         / \   \        3   4   6    """
    root = Node(1)
    root.left = Node(2)
    root.right = Node(5)

    root.left.left = Node(3)
    root.left.right = Node(4)

    root.right.right = Node(6)

    flatten(root)
    printFlattenedTree(root)
C#
using System;

/* Structure of a Binary Tree Node */
class Node {
    public int data;
    public Node left;
    public Node right;

    public Node(int val)
    {
        data = val;
        left = null;
        right = null;
    }
}

class GFG {
    static Node flattenTree(Node root, Node prev)
    {
        // Base case: empty tree
        if (root == null)
            return prev;

        // Process right subtree first
        prev = flattenTree(root.right, prev);

        // Process left subtree
        prev = flattenTree(root.left, prev);

        // Connect current node to previously processed node
        root.right = prev;

        // Left pointer must always be NULL
        root.left = null;

        // Update prev to current node
        prev = root;

        return prev;
    }

    static void flatten(Node root)
    {
        // Initialize previous node as NULL
        Node prev = null;

        prev = flattenTree(root, prev);
    }

    static void printFlattenedTree(Node root)
    {
        while (root!= null) {
            Console.Write(root.data + " ");
            root = root.right;
        }

        Console.WriteLine();
    }

    static void Main()
    {
        /*
                1
               / \
              2   5
             / \   \
            3   4   6
        */

        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(5);

        root.left.left = new Node(3);
        root.left.right = new Node(4);

        root.right.right = new Node(6);

        flatten(root);
        printFlattenedTree(root);
    }
}
JavaScript
/* Structure of a Binary Tree Node */
class Node {
    constructor(val)
    {
        this.data = val;
        this.left = null;
        this.right = null;
    }
}

function flattenTree(root, prev)
{
    // Base case: empty tree
    if (root === null)
        return prev;

    // Process right subtree first
    prev = flattenTree(root.right, prev);

    // Process left subtree
    prev = flattenTree(root.left, prev);

    // Connect current node to previously processed node
    root.right = prev;

    // Left pointer must always be NULL
    root.left = null;

    // Update prev to current node
    prev = root;

    return prev;
}

function flatten(root)
{
    // Initialize previous node as NULL
    let prev = null;

    prev = flattenTree(root, prev);
}

function printFlattenedTree(root)
{
    let res = "";
    while (root!== null) {
        res += root.data + " ";
        root = root.right;
    }

    console.log(res.trim());
}

// Driver Code

/*
           1
          / \
         2   5
        / \   \
       3   4   6
  */

let root = new Node(1);
root.left = new Node(2);
root.right = new Node(5);

root.left.left = new Node(3);
root.left.right = new Node(4);

root.right.right = new Node(6);

flatten(root);
printFlattenedTree(root);

Output
1 2 3 4 5 6 

[Expected Approach] Morris Traversal - O(n) Time and O(1) Space

The idea is to use Morris Traversal to flatten the tree in-place without recursion or a stack.

For each node with a left subtree, we connect the original right subtree to the rightmost node of the left subtree, then move the left subtree to the right, maintaining the Root -> Left -> Right preorder order while using O(1) extra space.

  • Start from the root and process each node while curr != null.
  • If curr has no left child, simply move to curr->right.
  • Otherwise, find the rightmost node of curr's left subtree.
  • Connect this rightmost node to curr->right (the original right subtree).
  • Move the left subtree to curr->right and set curr->left = null.
  • Move to curr->right and repeat until the entire tree is flattened.
C++
#include <bits/stdc++.h>
using namespace std;

/* Structure of a Binary Tree Node */
class Node
{
  public:
    int data;
    Node *left;
    Node *right;

    Node(int val)
    {
        data = val;
        left = nullptr;
        right = nullptr;
    }
};

void flatten(Node *root)
{
    Node *curr = root;

    while (curr!= nullptr)
    {
        // If left subtree exists
        if (curr->left!= nullptr)
        {
            // Find the rightmost node of the left subtree
            Node *predecessor = curr->left;

            while (predecessor->right!= nullptr)
                predecessor = predecessor->right;

            // Attach the original right subtree
            predecessor->right = curr->right;

            // Move the left subtree to the right
            curr->right = curr->left;

            // Left pointer must always be NULL
            curr->left = nullptr;
        }

        // Move to the next node
        curr = curr->right;
    }
}

void printFlattenedTree(Node *root)
{
    while (root!= nullptr)
    {
        cout << root->data << " ";
        root = root->right;
    }

    cout << endl;
}

int main()
{
    /*
            1
           / \
          2   5
         / \   \
        3   4   6
    */

    Node *root = new Node(1);
    root->left = new Node(2);
    root->right = new Node(5);

    root->left->left = new Node(3);
    root->left->right = new Node(4);

    root->right->right = new Node(6);

    flatten(root);
    printFlattenedTree(root);

    return 0;
}
Java
/* Structure of a Binary Tree Node */
class Node {
    int data;
    Node left;
    Node right;

    Node(int val)
    {
        data = val;
        left = null;
        right = null;
    }
}

class GFG {
    static void flatten(Node root)
    {
        Node curr = root;

        while (curr != null) {
            // If left subtree exists
            if (curr.left != null) {
                // Find the rightmost node of the left
                // subtree
                Node predecessor = curr.left;

                while (predecessor.right != null)
                    predecessor = predecessor.right;

                // Attach the original right subtree
                predecessor.right = curr.right;

                // Move the left subtree to the right
                curr.right = curr.left;

                // Left pointer must always be NULL
                curr.left = null;
            }

            // Move to the next node
            curr = curr.right;
        }
    }

    static void printFlattenedTree(Node root)
    {
        while (root != null) {
            System.out.print(root.data + " ");
            root = root.right;
        }

        System.out.println();
    }

    public static void main(String[] args)
    {
        /*
                1
               / \
              2   5
             / \   \
            3   4   6
        */

        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(5);

        root.left.left = new Node(3);
        root.left.right = new Node(4);

        root.right.right = new Node(6);

        flatten(root);
        printFlattenedTree(root);
    }
}
Python
# Structure of a Binary Tree Node
class Node:
    def __init__(self, val):
        self.data = val
        self.left = None
        self.right = None


def flatten(root):
    curr = root

    while curr is not None:

        # If left subtree exists
        if curr.left is not None:

            # Find the rightmost node of the left subtree
            predecessor = curr.left

            while predecessor.right is not None:
                predecessor = predecessor.right

            # Attach the original right subtree
            predecessor.right = curr.right

            # Move the left subtree to the right
            curr.right = curr.left

            # Left pointer must always be NULL
            curr.left = None

        # Move to the next node
        curr = curr.right


def printFlattenedTree(root):
    while root is not None:
        print(root.data, end=" ")
        root = root.right

    print()


# Driver Code
if __name__ == "__main__":
    """
            1
           / \
          2   5
         / \   \
        3   4   6
    """

    root = Node(1)
    root.left = Node(2)
    root.right = Node(5)

    root.left.left = Node(3)
    root.left.right = Node(4)

    root.right.right = Node(6)

    flatten(root)
    printFlattenedTree(root)
C#
using System;

/* Structure of a Binary Tree Node */
class Node {
    public int data;
    public Node left;
    public Node right;

    public Node(int val)
    {
        data = val;
        left = null;
        right = null;
    }
}

class GFG {
    static void flatten(Node root)
    {
        Node curr = root;

        while (curr != null) {
            // If left subtree exists
            if (curr.left != null) {
                // Find the rightmost node of the left
                // subtree
                Node predecessor = curr.left;

                while (predecessor.right != null)
                    predecessor = predecessor.right;

                // Attach the original right subtree
                predecessor.right = curr.right;

                // Move the left subtree to the right
                curr.right = curr.left;

                // Left pointer must always be NULL
                curr.left = null;
            }

            // Move to the next node
            curr = curr.right;
        }
    }

    static void printFlattenedTree(Node root)
    {
        while (root != null) {
            Console.Write(root.data + " ");
            root = root.right;
        }

        Console.WriteLine();
    }

    static void Main()
    {
        /*
                1
               / \
              2   5
             / \   \
            3   4   6
        */

        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(5);

        root.left.left = new Node(3);
        root.left.right = new Node(4);

        root.right.right = new Node(6);

        flatten(root);
        printFlattenedTree(root);
    }
}
JavaScript
/* Structure of a Binary Tree Node */
class Node {
    constructor(val)
    {
        this.data = val;
        this.left = null;
        this.right = null;
    }
}

function flatten(root)
{
    let curr = root;

    while (curr !== null) {

        // If left subtree exists
        if (curr.left !== null) {

            // Find the rightmost node of the left subtree
            let predecessor = curr.left;

            while (predecessor.right !== null)
                predecessor = predecessor.right;

            // Attach the original right subtree
            predecessor.right = curr.right;

            // Move the left subtree to the right
            curr.right = curr.left;

            // Left pointer must always be NULL
            curr.left = null;
        }

        // Move to the next node
        curr = curr.right;
    }
}

function printFlattenedTree(root)
{
    let res = "";
    while (root !== null) {
        res += root.data + " ";
        root = root.right;
    }

    console.log(res.trim());
}

// Driver code

/*
           1
          / \
         2   5
        / \   \
       3   4   6
   */

let root = new Node(1);
root.left = new Node(2);
root.right = new Node(5);

root.left.left = new Node(3);
root.left.right = new Node(4);

root.right.right = new Node(6);

flatten(root);
printFlattenedTree(root);

Output
1 2 3 4 5 6 
Comment