Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Tree
  • Practice Tree
  • MCQs on Tree
  • Tutorial on Tree
  • Types of Trees
  • Basic operations
  • Tree Traversal
  • Binary Tree
  • Complete Binary Tree
  • Ternary Tree
  • Binary Search Tree
  • Red-Black Tree
  • AVL Tree
  • Full Binary Tree
  • B-Tree
  • Advantages & Disadvantages
Open In App
Next Article:
Print nodes in top view of Binary Tree | Set 2
Next article icon

Flatten a binary tree into linked list

Last Updated : 07 Nov, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Given a binary tree, flatten it into linked list in-place. Usage of auxiliary data structure is not allowed. After flattening, left of each node should point to NULL and right should contain next node in preorder.

Examples: 

Input : 
1
/ \
2 5
/ \ \
3 4 6
Output :
1
\
2
\
3
\
4
\
5
\
6
Input :
1
/ \
3 4
/
2
\
5
Output :
1
\
3
\
4
\
2
\
5
Recommended Practice
Flatten binary tree to linked list
Try It!

Simple Approach: A simple solution is to use Level Order Traversal using Queue. In level order traversal, keep track of previous node. Make current node as right child of previous and left of previous node as NULL. This solution requires queue, but question asks to solve without additional data structure.

Efficient Without Additional Data Structure Recursively look for the node with no grandchildren and both left and right child in the left sub-tree. Then store node->right in temp and make node->right=node->left. Insert temp in first node NULL on right of node by node=node->right. Repeat until it is converted to linked list. Even though this approach does not require additional data structure , but still it takes space for Recursion stack.

For Example, 

Flatten Binary Tree Example

Implementation:

C++




// C++ Program to flatten a given Binary Tree into linked
// list by using Morris Traversal concept
#include <bits/stdc++.h>
using namespace std;
 
struct Node {
    int key;
    Node *left, *right;
};
 
// utility that allocates a new Node with the given key
Node* newNode(int key)
{
    Node* node = new Node;
    node->key = key;
    node->left = node->right = NULL;
    return (node);
}
 
// Function to convert binary tree into linked list by
// altering the right node and making left node point to
// NULL
void flatten(struct Node* root)
{
    // base condition- return if root is NULL or if it is a
    // leaf node
    if (root == NULL || root->left == NULL && root->right == NULL)
        return;
    // if root->left exists then we have to make it
    // root->right
    if (root->left != NULL) {
        // move left recursively
        flatten(root->left);
        // store the node root->right
        struct Node* tmpRight = root->right;
        root->right = root->left;
        root->left = NULL;
        // find the position to insert the stored value
        struct Node* t = root->right;
        while (t->right != NULL)
            t = t->right;
        // insert the stored value
        t->right = tmpRight;
    }
    // now call the same function for root->right
    flatten(root->right);
}
 
// To find the inorder traversal
void inorder(struct Node* root)
{
    // base condition
    if (root == NULL)
        return;
    inorder(root->left);
    cout << root->key << " ";
    inorder(root->right);
}
 
/* Driver program to test above functions*/
int main()
{
    /*    1
        /   \
       2     5
      / \     \
     3   4     6 */
    Node* root = newNode(1);
    root->left = newNode(2);
    root->right = newNode(5);
    root->left->left = newNode(3);
    root->left->right = newNode(4);
    root->right->right = newNode(6);
    flatten(root);
    cout << "The Inorder traversal after flattening binary tree ";
    inorder(root);
    return 0;
}
 
// This code is contributed by Aditya Kumar (adityakumar129)
 
 

C




// C Program to flatten a given Binary Tree into linked
// list
#include <stdio.h>
#include <stdlib.h>
 
typedef struct Node {
    int key;
    struct Node *left, *right;
}Node;
 
// utility that allocates a new Node with the given key
Node* newNode(int key)
{
    Node* node = (Node*)malloc(sizeof(Node));
    node->key = key;
    node->left = node->right = NULL;
    return (node);
}
 
// Function to convert binary tree into linked list by
// altering the right node and making left node point to
// NULL
void flatten(Node* root)
{
    // base condition- return if root is NULL or if it is a
    // leaf node
    if (root == NULL || root->left == NULL && root->right == NULL)
        return;
 
    // if root->left exists then we have to make it
    // root->right
    if (root->left != NULL) {
        // move left recursively
        flatten(root->left);
        // store the node root->right
        struct Node* tmpRight = root->right;
        root->right = root->left;
        root->left = NULL;
        // find the position to insert the stored value
        struct Node* t = root->right;
        while (t->right != NULL)
            t = t->right;
        // insert the stored value
        t->right = tmpRight;
    }
 
    // now call the same function for root->right
    flatten(root->right);
}
 
// To find the inorder traversal
void inorder(struct Node* root)
{
    // base condition
    if (root == NULL)
        return;
    inorder(root->left);
    printf("%d ", root->key);
    inorder(root->right);
}
 
/* Driver program to test above functions*/
int main()
{
    /*    1
        /   \
       2     5
      / \     \
     3   4     6 */
    Node* root = newNode(1);
    root->left = newNode(2);
    root->right = newNode(5);
    root->left->left = newNode(3);
    root->left->right = newNode(4);
    root->right->right = newNode(6);
 
    flatten(root);
 
    printf("The Inorder traversal after flattening binary tree ");
    inorder(root);
    return 0;
}
 
// This code is contributed by aditykumar129.
 
 

Java




// Java program to flatten a given Binary Tree into linked
// list
 
// A binary tree node
class Node {
    int data;
    Node left, right;
    Node(int key)
    {
        data = key;
        left = right = null;
    }
}
 
class BinaryTree {
 
    Node root;
 
    // Function to convert binary tree into linked list by
    // altering the right node and making left node NULL
    public void flatten(Node node)
    {
        // Base case - return if root is NULL
        if (node == null)
            return;
        // Or if it is a leaf node
        if (node.left == null && node.right == null)
            return;
        // If root.left children exists then we have to make
        // it node.right (where node is root)
        if (node.left != null) {
            // Move left recursively
            flatten(node.left);
            // Store the node.right in Node named tempNode
            Node tempNode = node.right;
            node.right = node.left;
            node.left = null;
            // Find the position to insert the stored value
            Node curr = node.right;
            while (curr.right != null)
                curr = curr.right;
            // Insert the stored value
            curr.right = tempNode;
        }
        // Now call the same function for node.right
        flatten(node.right);
    }
    // Function for Inorder traversal
    public void inOrder(Node node)
    {
        // Base Condition
        if (node == null)
            return;
        inOrder(node.left);
        System.out.print(node.data + " ");
        inOrder(node.right);
    }
 
    // Driver code
    public static void main(String[] args)
    {
        BinaryTree tree = new BinaryTree();
 
        /*    1
            /   \
           2     5
          / \     \
         3   4     6 */
 
        tree.root = new Node(1);
        tree.root.left = new Node(2);
        tree.root.right = new Node(5);
        tree.root.left.left = new Node(3);
        tree.root.left.right = new Node(4);
        tree.root.right.right = new Node(6);
 
        System.out.println(
            "The Inorder traversal after flattening binary tree ");
        tree.flatten(tree.root);
        tree.inOrder(tree.root);
    }
}
 
// This code is contributed by Aditya Kumar (adityakumar129)
 
 

Python3




# Python3 program to flatten a given Binary
# Tree into linked list
class Node:
     
    def __init__(self):
         
        self.key = 0
        self.left = None
        self.right = None
 
# Utility that allocates a new Node
# with the given key
def newNode(key):
     
    node = Node()
    node.key = key
    node.left = node.right = None
    return (node)
 
# Function to convert binary tree into
# linked list by altering the right node
# and making left node point to None
def flatten(root):
 
    # Base condition- return if root is None
    # or if it is a leaf node
    if (root == None or root.left == None and
                        root.right == None):
        return
     
    # If root.left exists then we have
    # to make it root.right
    if (root.left != None):
 
        # Move left recursively
        flatten(root.left)
    
        # Store the node root.right
        tmpRight = root.right
        root.right = root.left
        root.left = None
 
        # Find the position to insert
        # the stored value  
        t = root.right
        while (t.right != None):
            t = t.right
 
        # Insert the stored value
        t.right = tmpRight
 
    # Now call the same function
    # for root.right
    flatten(root.right)
 
# To find the inorder traversal
def inorder(root):
 
    # Base condition
    if (root == None):
        return
     
    inorder(root.left)
    print(root.key, end = ' ')
    inorder(root.right)
 
# Driver Code
if __name__=='__main__':
     
    '''   1
        /   \
       2     5
      / \     \
     3   4     6 '''
    root = newNode(1)
    root.left = newNode(2)
    root.right = newNode(5)
    root.left.left = newNode(3)
    root.left.right = newNode(4)
    root.right.right = newNode(6)
 
    flatten(root)
 
    print("The Inorder traversal after "
          "flattening binary tree ",
          end = '')
    inorder(root)
 
# This code is contributed by pratham76
 
 

C#




// C# program to flatten a given
// Binary Tree into linked list
using System;
 
// A binary tree node
class Node
{
  public int data;
  public Node left, right;
 
  public Node(int key)
  {
    data = key;
    left = right = null;
  }
}
 
class BinaryTree
{   
  Node root;
 
  // Function to convert binary tree into
  // linked list by altering the right node
  // and making left node NULL
  public void flatten(Node node)
  {
 
    // Base case - return if root is NULL
    if (node == null)
      return;
 
    // Or if it is a leaf node
    if (node.left == null &&
        node.right == null)
      return;
 
    // If root.left children exists then we have
    // to make it node.right (where node is root)
    if (node.left != null)
    {
 
      // Move left recursively
      flatten(node.left);
 
      // Store the node.right in
      // Node named tempNode
      Node tempNode = node.right;
      node.right = node.left;
      node.left = null;
 
      // Find the position to insert
      // the stored value
      Node curr = node.right;
      while (curr.right != null)
      {
        curr = curr.right;
      }
 
      // Insert the stored value
      curr.right = tempNode;
    }
 
    // Now call the same function
    // for node.right
    flatten(node.right);
 
  }
 
  // Function for Inorder traversal
  public void inOrder(Node node)
  {
 
    // Base Condition
    if (node == null)
      return;
    inOrder(node.left);
    Console.Write(node.data + " ");
    inOrder(node.right);
  }
 
  // Driver code
  public static void Main(string[] args)
  {
    BinaryTree tree = new BinaryTree();
 
    /* 1
        / \
    2     5
    / \     \
    3 4     6 */
 
    tree.root = new Node(1);
    tree.root.left = new Node(2);
    tree.root.right = new Node(5);
    tree.root.left.left = new Node(3);
    tree.root.left.right = new Node(4);
    tree.root.right.right = new Node(6);
    Console.Write("The Inorder traversal after " +
                  "flattening binary tree ");                       
    tree.flatten(tree.root);
    tree.inOrder(tree.root);
  }
}
 
// This code is contributed by rutvik_56
 
 

Javascript




<script>
 
// Javascript program to flatten a given
// Binary Tree into linked list
 
// A binary tree node
class Node
{
    constructor(key)
    {
        this.data = key;
        this.left = null;
        this.right = null;
    }
}
 
var root;
 
// Function to convert binary tree into
// linked list by altering the right node
// and making left node NULL
function flatten(node)
{
     
    // Base case - return if root is NULL
    if (node == null)
        return;
         
    // Or if it is a leaf node
    if (node.left == null &&
        node.right == null)
        return;
         
    // If root.left children exists then we have
    // to make it node.right (where node is root)
    if (node.left != null)
    {
         
        // Move left recursively
        flatten(node.left);
         
        // Store the node.right in
        // Node named tempNode
        var tempNode = node.right;
        node.right = node.left;
        node.left = null;
         
        // Find the position to insert
        // the stored value
        var curr = node.right;
        while (curr.right != null)
        {
            curr = curr.right;
        }
         
        // Insert the stored value
        curr.right = tempNode;
    }
     
    // Now call the same function
    // for node.right
    flatten(node.right);
}
 
// Function for Inorder traversal
function inOrder(node)
{
     
    // Base Condition
    if (node == null)
        return;
         
    inOrder(node.left);
    document.write(node.data + " ");
    inOrder(node.right);
}
 
// Driver code
/*   1
    / \
  2     5
 / \     \
3   4     6 */
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);
 
document.write("The Inorder traversal after " +
               "flattening binary tree ");                       
flatten(root);
inOrder(root);
 
// This code is contributed by famously
 
</script>
 
 
Output
The Inorder traversal after flattening binary tree 1 2 3 4 5 6        

Complexity Analysis:

  • Time Complexity: O(n), traverse the whole tree
  • Space Complexity: O(n), Extra space used for recursion call.

Another Approach:
We will use the intuition behind Morris’s traversal. In Morris Traversal we use the concept of a threaded binary tree.

  • At a node(say cur) if there exists a left child, we will find the rightmost node in the left subtree(say prev).
  • We will set prev’s right child to cur’s right child,
  • We will then set cur’s right child to it’s left child.
  • We will then move cur to the next node by assigning cur it to its right child
  • We will stop the execution when cur points to NULL.

Implementation:

C++




// C++ Program to flatten a given Binary Tree into linked
// list
#include <bits/stdc++.h>
using namespace std;
 
struct Node {
    int key;
    Node *left, *right;
};
 
// utility that allocates a new Node with the given key
Node* newNode(int key)
{
    Node* node = new Node;
    node->key = key;
    node->left = node->right = NULL;
    return (node);
}
 
// Function to convert binary tree into linked list by
// altering the right node and making left node point to
// NULL
void flatten(Node* root)
{
    // traverse till root is not NULL
    while (root) {
        // if root->left is not NULL
        if (root->left != NULL) {
            // set curr node as root->left;
            Node* curr = root->left;
            // traverse to the extreme right of curr
            while (curr->right) {
                curr = curr->right;
            }
            // join curr->right to root->right
            curr->right = root->right;
            // put root->left to root->right
            root->right = root->left;
            // make root->left as NULL
            root->left = NULL;
        }
        // now go to the right of the root
        root = root->right;
    }
}
 
// To find the inorder traversal
void inorder(struct Node* root)
{
    // base condition
    if (root == NULL)
        return;
    inorder(root->left);
    cout << root->key << " ";
    inorder(root->right);
}
 
/* Driver program to test above functions*/
int main()
{
    /*    1
        /   \
       2     5
      / \     \
     3   4     6 */
    Node* root = newNode(1);
    root->left = newNode(2);
    root->right = newNode(5);
    root->left->left = newNode(3);
    root->left->right = newNode(4);
    root->right->right = newNode(6);
    flatten(root);
    cout << "The Inorder traversal after flattening binary "
            "tree ";
    inorder(root);
    return 0;
}
 
// This code is contributed by Harsh Raghav
 
 

Java




// Java Program to flatten a given Binary Tree into linked
// list
import java.io.*;
 
class Node {
  int key;
  Node left, right;
}
 
class GFG {
 
  // utility that allocates a new Node with the given key
  static Node newNode(int key)
  {
    Node node = new Node();
    node.key = key;
    node.left = node.right = null;
    return node;
  }
 
  // Function to convert binary tree into linked list by
  // altering the right node and making left node point to
  // NULL
  static void flatten(Node root)
  {
    // traverse till root is not NULL
    while (root != null) {
      // if root->left is not NULL
      if (root.left != null) {
        // set curr node as root->left;
        Node curr = root.left;
        // traverse to the extreme right of curr
        while (curr.right != null) {
          curr = curr.right;
        }
        // join curr->right to root->right
        curr.right = root.right;
        // put root->left to root->right
        root.right = root.left;
        // make root->left as NULL
        root.left = null;
      }
      // now go to the right of the root
      root = root.right;
    }
  }
 
  // To find the inorder traversal
  static void inorder(Node root)
  {
    // base condition
    if (root == null) {
      return;
    }
    inorder(root.left);
    System.out.print(root.key + " ");
    inorder(root.right);
  }
 
  public static void main(String[] args)
  {
 
    /*    1
            /   \
              2     5
            / \     \
          3   4     6  */
 
    Node root = newNode(1);
    root.left = newNode(2);
    root.right = newNode(5);
    root.left.left = newNode(3);
    root.left.right = newNode(4);
    root.right.right = newNode(6);
    flatten(root);
 
    System.out.print(
      "The Inorder traversal after flattening binary tree ");
    inorder(root);
  }
}
 
// This code is contributed by lokesh.
 
 

Python3




# Python3 program to flatten a given Binary
# Tree into linked list
class Node:
     
    def __init__(self):
         
        self.key = 0
        self.left = None
        self.right = None
 
def newNode(key):
    node = Node()
    node.key = key
    node.left = node.right = None
    return (node)
 
# Function to convert binary tree into
# linked list by altering the right node
# and making left node point to None
def flatten(root):
     
    # traverse till root is not None
    while(root != None):
        # if root.left is not None
        if(root.left != None):
            # set curr node as root.left
            curr = root.left
            # traverse to the extreme right of curr
            while(curr.right != None):
                curr = curr.right
            # join curr.right to root.right
            curr.right = root.right
            # put root.left to root.right
            root.right = root.left
            # make root.left as None
            root.left = None
        # now go to the right of the root
        root = root.right
         
         
# To find the inorder traversal
def inorder(root):
 
    # Base condition
    if (root == None):
        return
     
    inorder(root.left)
    print(root.key, end = ' ')
    inorder(root.right)
 
# Driver Code
if __name__=='__main__':
     
    '''   1
        /   \
       2     5
      / \     \
     3   4     6 '''
    root = newNode(1)
    root.left = newNode(2)
    root.right = newNode(5)
    root.left.left = newNode(3)
    root.left.right = newNode(4)
    root.right.right = newNode(6)
 
    flatten(root)
 
    print("The Inorder traversal after "
          "flattening binary tree ",
          end = '')
    inorder(root)
 
# This code is contributed by Yash Agarwal(yashagarwal2852002)
 
 

C#




// C# program to flatten a given Binary Tree into linked list
using System;
 
class Node
{
  public int data;
  public Node left, right;
 
  public Node(int key)
  {
    data = key;
    left = right = null;
  }
}
 
class BinaryTree
{   
  Node root;
 
  // Function to convert binary tree into
  // linked list by altering the right node
  // and making left node NULL
  public void flatten(Node node)
  {
      // traverse till node is not NULL
      while(node != null){
          // if node->left is not NULL
          if(node.left != null){
              // set curr node as node->left;
              Node curr = node.left;
              // traverse to the extreme right of curr
              while(curr.right != null){
                  curr = curr.right;
              }
              // join curr->right to node->right
              curr.right = node.right;
              // put node->left to node->right
              node.right = node.left;
              // make node->left as NULL
              node.left = null;
          }
          // now go to the right of the node
          node = node.right;
      }
  }
 
  // Function for Inorder traversal
  public void inorder(Node node)
  {
    // Base Condition
    if (node == null)
      return;
    inorder(node.left);
    Console.Write(node.data + " ");
    inorder(node.right);
  }
 
 // Driver program to test above functions
  public static void Main(string[] args)
  {
    BinaryTree tree = new BinaryTree();
 
    /*   1
        / \
       2   5
      / \   \
      3 4    6 */
 
    tree.root = new Node(1);
    tree.root.left = new Node(2);
    tree.root.right = new Node(5);
    tree.root.left.left = new Node(3);
    tree.root.left.right = new Node(4);
    tree.root.right.right = new Node(6);
    Console.Write("The Inorder traversal after " +
                  "flattening binary tree ");                       
    tree.flatten(tree.root);
    tree.inorder(tree.root);
  }
}
 
// This code is contributed by Yash Agarwal(yashagarwal2852002)
 
 

Javascript




<script>
// Javascript program to flatten a given
// Binary Tree into linked list
 
// A binary tree node
class Node
{
    constructor(key)
    {
        this.data = key;
        this.left = null;
        this.right = null;
    }
}
 
var root;
// Function to convert binary tree into linked list by
// altering the right node and making left node NULL
function flatten(root)
{
    // traverse till root is not NULL
    while(root){
        if(root.left != null){
            curr = root.left;
            // traverse to the extreme right of curr
            while(curr.right){
                curr = curr.right;
            }
            curr.right = root.right;
            root.right = root.left;
            root.left = null;
        }
        root = root.right;
    }
     
}
 
// To find the inorder traversal
function inorder(root)
{
    // base condition
    if (root == null)
        return;
         
    inorder(root.left);
    console.log(root.data + " ");
    inorder(root.right);
}
 
// Driver code
/*   1
    / \
  2     5
 / \     \
3   4     6 */
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);
 
console.log("The Inorder traversal after " +
               "flattening binary tree ");                       
flatten(root);
inorder(root);
 
// This code is contributed by Yash Agarwal(yashagarwal2852002)
</script>
 
 
Output
The Inorder traversal after flattening binary tree 1 2 3 4 5 6        

Time Complexity: O(N) Time complexity will be the same as that of a Morris’s traversal
Auxiliary Space: O(1)

Another Approach Using Stack:

In this solution, we start by initializing a prev variable to None. This variable will keep track of the previously flattened node as we recursively flatten the binary tree.

  • We then define a recursive function flatten that takes in the root node of the binary tree. This function does not return anything, but instead modifies the tree in-place.
  • The first thing we do in the flatten function is to check if the root node is None. If it is, we simply return.
  • Next, we recursively flatten the right subtree of the root node by calling self.flatten(root.right). This will flatten the right subtree and set self.prev to the rightmost node in the right subtree.
  • We then recursively flatten the left subtree of the root node by calling self.flatten(root.left). This will flatten the left subtree and update self.prev to the rightmost node in the flattened left subtree.
  • Once we have flattened both the left and right subtrees, we update the root.right pointer to be the previously flattened node (self.prev). We also set the root.left pointer to None to remove the left child.
  • Finally, we update self.prev to be the current node (root). This is important because it allows us to keep track of the previously flattened node as we continue to recursively flatten the tree.

This algorithm flattens the binary tree in pre-order traversal, so the resulting “linked list” will be in the same order as a pre-order traversal of the tree.

Implementation:

C++




// C++ Program to flatten a given Binary Tree into linked
// list
#include <bits/stdc++.h>
using namespace std;
 
struct Node {
    int key;
    Node *left, *right;
};
 
// utility that allocates a new Node with the given key
Node* newNode(int key)
{
    Node* node = new Node;
    node->key = key;
    node->left = node->right = NULL;
    return (node);
}
 
// Function to convert binary tree into linked list by
// altering the right node and making left node point to
// NULL
 
void flatten(Node* root)
    {
  // Base case: if the current node is null, return null
        stack<Node *>st;
        st.push(root);
  // If the left subtree was flattened, merge it with the current node
   // If the right subtree was flattened, return its tail node
   // If neither subtree was flattened, return the current node as the tail node
        while(st.empty()!=true)
        {
            Node *curr = st.top();
            st.pop();
            if(curr==NULL) return;
            if(curr->right!=NULL) st.push(curr->right);// Connect the right subtree of the left tail to the right subtree of the current node
            if(curr->left!=NULL) st.push(curr->left);// Make the left subtree the new right subtree of the current node
            if(st.empty()!=true)// Set the left child of the current node to null
            {
                curr->right = st.top();
            }
            curr->left = NULL;
        }
        return;
    }
 
void inorder(struct Node* root)
{
    // base condition
    if (root == NULL)
        return;
    inorder(root->left);
    cout << root->key << " ";
    inorder(root->right);
}
 
int main()
{
    /*    1
        /   \
       2     5
      / \     \
     3   4     6 */
    Node* root = newNode(1);
    root->left = newNode(2);
    root->right = newNode(5);
    root->left->left = newNode(3);
    root->left->right = newNode(4);
    root->right->right = newNode(6);
  // Call the recursive helper function
    flatten(root);
    cout << "The Inorder traversal after flattening binary "
            "tree ";
    inorder(root);
    return 0;
}
 
 

Java




import java.io.*;
import java.util.Stack;
 
class Node {
    int key;
    Node left, right;
 
    Node(int item) {
        key = item;
        left = right = null;
    }
}
public class GFG {
    // Function to flatten binary tree into
  // linked list
    public static void flatten(Node root) {
        if (root == null) {
            return;
        }
        Stack<Node> stack = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            Node current = stack.pop();
 
            if (current.right != null) {
                stack.push(current.right);
            }
 
            if (current.left != null) {
                stack.push(current.left);
            }
 
            if (!stack.isEmpty()) {
                current.right = stack.peek();
            }
 
            current.left = null;
        }
    }
    // Function to perform an inorder traversal and
  // print the elements
    public static void inorder(Node root) {
        if (root == null) {
            return;
        }
        inorder(root.left);
        System.out.print(root.key + " ");
        inorder(root.right);
    }
    public static void main(String[] args) {
        /* Construct the binary tree:
           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 the binary tree into a linked list
        flatten(root);
        System.out.print("Inorder traversal after flattening binary tree ");
        inorder(root);
    }
}
 
 

Python3




class TreeNode:
    def __init__(self, key):
        self.key = key
        self.left = None
        self.right = None
 
def flatten(root):
    if not root:
        return
 
    stack = [root]
 
    while stack:
        curr = stack.pop()
        if not curr:
            continue
 
        if curr.right:
            stack.append(curr.right)  # Connect the right subtree of the left tail to the right subtree of the current node
        if curr.left:
            stack.append(curr.left)  # Make the left subtree the new right subtree of the current node
 
        if stack:
            curr.right = stack[-1]
        curr.left = None
 
def inorder(root):
    if not root:
        return
    inorder(root.left)
    print(root.key, end=' ')
    inorder(root.right)
 
# Main function
if __name__ == "__main__":
    # Construct the binary tree
    #       1
    #      / \
    #     2   5
    #    / \   \
    #   3   4   6
    root = TreeNode(1)
    root.left = TreeNode(2)
    root.right = TreeNode(5)
    root.left.left = TreeNode(3)
    root.left.right = TreeNode(4)
    root.right.right = TreeNode(6)
 
    # Call the flatten function
    flatten(root)
 
    print("The Inorder traversal after flattening binary tree:")
    inorder(root)
     
     
# This code is contributed by shivamgupta0987654321
 
 

C#




using System;
using System.Collections.Generic;
 
public class Node {
    public int key;
    public Node left, right;
}
 
public class FlattenBinaryTreeToLinkedList {
 
    // Utility function to create a new Node with the given key
    static Node NewNode(int key) {
        Node node = new Node();
        node.key = key;
        node.left = node.right = null;
        return node;
    }
 
    // Function to flatten a binary tree into a linked list
    static void Flatten(Node root) {
        if (root == null) return;
 
        // Create a stack to perform a preorder traversal of the binary tree
        Stack<Node> stack = new Stack<Node>();
        stack.Push(root);
 
        while (stack.Count != 0) {
            Node curr = stack.Pop();
            if (curr == null) continue;
 
            // Push the right and left children onto the stack (preorder)
            if (curr.right != null) stack.Push(curr.right);
            if (curr.left != null) stack.Push(curr.left);
 
            if (stack.Count != 0) {
                // Set the current node's right pointer to the next node in the stack
                curr.right = stack.Peek();
            }
            // Clear the left pointer as we are converting the tree to a linked list
            curr.left = null;
        }
    }
 
    // Function to perform an inorder traversal of the binary tree
    static void Inorder(Node root) {
        if (root == null) return;
        Inorder(root.left);
        Console.Write(root.key + " "); // Print the current node's key
        Inorder(root.right);
    }
 
    public static void Main(string[] args) {
        // Create a sample binary tree
        Node root = NewNode(1);
        root.left = NewNode(2);
        root.right = NewNode(5);
        root.left.left = NewNode(3);
        root.left.right = NewNode(4);
        root.right.right = NewNode(6);
 
        // Call the Flatten function to convert the tree to a linked list
        Flatten(root);
 
        // Print the inorder traversal of the flattened binary tree (linked list)
        Console.Write("The Inorder traversal after flattening binary tree ");
        Inorder(root);
    }
}
 
 

Javascript




class TreeNode {
    constructor(key) {
        this.key = key;
        this.left = null;
        this.right = null;
    }
}
 
// Function to convert a binary tree into a linked list by altering the right node and making the left node point to null
function flatten(root) {
    // Base case: if the current node is null, return null
    const stack = [root];
 
    // If the left subtree was flattened, merge it with the current node
    // If the right subtree was flattened, return its tail node
    // If neither subtree was flattened, return the current node as the tail node
    while (stack.length > 0) {
        const curr = stack.pop();
        if (curr === null) {
            return;
        }
        if (curr.right !== null) {
            stack.push(curr.right); // Connect the right subtree of the left tail to the right subtree of the current node
        }
        if (curr.left !== null) {
            stack.push(curr.left); // Make the left subtree the new right subtree of the current node
        }
        if (stack.length > 0) {
            curr.right = stack[stack.length - 1];
        }
        curr.left = null;
    }
}
 
// Function to perform an inorder traversal of the tree
function inorder(root) {
    // Base condition
    if (root === null) {
        return;
    }
    inorder(root.left);
    console.log(root.key + " ");
    inorder(root.right);
}
 
// Main function
function main() {
    /*    1
        /   \
       2     5
      / \     \
     3   4     6 */
    const root = new TreeNode(1);
    root.left = new TreeNode(2);
    root.right = new TreeNode(5);
    root.left.left = new TreeNode(3);
    root.left.right = new TreeNode(4);
    root.right.right = new TreeNode(6);
 
    // Call the flatten function
    flatten(root);
    console.log("The Inorder traversal after flattening binary tree:");
    inorder(root);
}
 
// Run the main function
main();
 
 
Output
The Inorder traversal after flattening binary tree 1 2 3 4 5 6        

Time Complexity: O(N), The loop will execute for every node once.
Space Complexity: O(N), Auxiliary Stack Space is needed.



Next Article
Print nodes in top view of Binary Tree | Set 2

A

aastha98
Improve
Article Tags :
  • C++
  • C++ Programs
  • Data Structures
  • DSA
  • Recursion
  • Tree
Practice Tags :
  • CPP
  • Data Structures
  • Recursion
  • Tree

Similar Reads

  • Flatten a binary tree into linked list | Set-2
    Given a binary tree, flatten it into a linked list. After flattening, the left of each node should point to NULL and right should contain next node in level order. Example: Input: 1 / \ 2 5 / \ \ 3 4 6 Output: 1 \ 2 \ 3 \ 4 \ 5 \ 6 Input: 1 / \ 3 4 / 2 \ 5 Output: 1 \ 3 \ 4 \ 2 \ 5 Approach: An appr
    9 min read
  • Flatten Binary Tree in order of Zig Zag traversal
    Given a Binary Tree, the task is to flatten it in order of ZigZag traversal of the tree. In the flattened binary tree, the left node of all the nodes must be NULL.Examples: Input: 1 / \ 5 2 / \ / \ 6 4 9 3 Output: 1 2 5 6 4 9 3 Input: 1 \ 2 \ 3 \ 4 \ 5 Output: 1 2 3 4 5 Approach: We will solve this
    7 min read
  • How to Print Data in Binary Tree Level by Level in C++?
    A binary tree is a non-linear hierarchical data structure where each node can have at most two children which are termed as left and right child. In this article, we will learn how to print data in a binary tree level by level in C++. Example Input: 10 / \ 20 30 / \ / \40 50 60 70Output:10 20 30 40
    4 min read
  • Print nodes in top view of Binary Tree | Set 2
    Top view of a binary tree is the set of nodes visible when the tree is viewed from the top. Given a binary tree, print the top view of it. The output nodes should be printed from left to right. Note: A node x is there in output if x is the topmost node at its horizontal distance. Horizontal distance
    14 min read
  • Binary Search Tree in C++
    A Binary Search Tree (BST) is a type of binary tree in which the data is organized and stored in a sorted order. Unlike, a binary tree that doesn't follow a specific order for node placement, in a binary search tree all the elements on the left side of a node are smaller than the node itself, and el
    10 min read
  • C++ Program For Reversing A Doubly Linked List
    Given a Doubly Linked List, the task is to reverse the given Doubly Linked List. See below diagrams for example.  (a) Original Doubly Linked List (b) Reversed Doubly Linked List Here is a simple method for reversing a Doubly Linked List. All we need to do is swap prev and next pointers for all nodes
    5 min read
  • C++ Program To Flatten A Multi-Level Linked List Depth Wise- Set 2
    We have discussed flattening of a multi-level linked list where nodes have two pointers down and next. In the previous post, we flattened the linked list level-wise. How to flatten a linked list when we always need to process the down pointer before next at every node. Input: 1 - 2 - 3 - 4 | 7 - 8 -
    4 min read
  • Convert Binary Tree to Circular Doubly Linked List using Linear extra space
    Given a Binary Tree, convert it to a Circular Doubly Linked List. The left and right pointers in nodes are to be used as previous and next pointers, respectively, in the converted Circular Linked List.The order of nodes in the List must be the same as in the order of the given Binary Tree.The first
    12 min read
  • Inorder Tree Traversal of Binary Tree in C++
    A binary tree is a non-linear hierarchical data structure in which each node has at most two children known as the left child and the right child. As the binary tree has non-linear structure it can be traversed in multiple ways one such way is in-order traversal which is a depth first (DFS) traversa
    4 min read
  • Connect all nodes to their Left Neighbors in a Binary Tree
    Given a Binary Tree, where each node contains an extra empty pointer initially null. The task is to connect all nodes of the binary tree to their left neighbor at the same level using this extra pointer.Examples: Input : A / \ B C / \ \ D E F Output : NULL<--A / \ NULL<--B<--C / \ \ NULL
    10 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences