Skip to content
Related Articles

Related Articles

Improve Article

Create a sorted linked list from the given Binary Tree

  • Difficulty Level : Medium
  • Last Updated : 21 Jun, 2021

Given a binary tree, the task is to convert it into a sorted linked list.
Examples: 
 

Input:
     1   
   /  \  
  2    3 
Output: 1 2 3

Input:
        2
      /   \
     4     8
   /  \   / \
  7   3  5   1
Output: 1 2 3 4 5 7 8

Input:
        3   
       /  
      4 
     / 
    1
   /
  9
Output: 1 3 4 9

 

Approach: Recursively iterate the given binary tree and add each node to its correct position in the resultant linked list (initially empty) using insertion sort.
Below is the implementation of the above approach: 
 

C++




// C++ implementation of the approach
#include <iostream>
using namespace std;
 
// A linked list node
class Node {
public:
    int data;
    Node* next;
    Node(int data)
    {
        this->data = data;
        this->next = NULL;
    }
};
 
// A binary tree node
class treeNode {
public:
    int data;
    treeNode* left;
    treeNode* right;
    treeNode(int data)
    {
        this->data = data;
        this->left = NULL;
        this->right = NULL;
    }
};
 
// Function to print the linked list
void print(Node* head)
{
    if (head == NULL) {
        return;
    }
    Node* temp = head;
    while (temp != NULL) {
        cout << temp->data << " ";
        temp = temp->next;
    }
}
 
// Function to create Linked list from given binary tree
Node* sortedList(Node* head, treeNode* root)
{
    // return head if root is null
    if (root == NULL) {
        return head;
    }
 
    // First make the sorted linked list
    // of the left sub-tree
    head = sortedList(head, root->left);
    Node* newNode = new Node(root->data);
    Node* temp = head;
    Node* prev = NULL;
 
    // If linked list is empty add the
    // node to the head
    if (temp == NULL) {
        head = newNode;
    }
    else {
 
        // Find the correct position of the node
        // in the given linked list
        while (temp != NULL) {
            if (temp->data > root->data) {
                break;
            }
            else {
                prev = temp;
                temp = temp->next;
            }
        }
 
        // Given node is to be attached
        // at the end of the list
        if (temp == NULL) {
            prev->next = newNode;
        }
        else {
 
            // Given node is to be attached
            // at the head of the list
            if (prev == NULL) {
                newNode->next = temp;
                head = newNode;
            }
            else {
 
                // Insertion in between the list
                newNode->next = temp;
                prev->next = newNode;
            }
        }
    }
 
    // Now add the nodes of the right sub-tree
    // to the sorted linked list
    head = sortedList(head, root->right);
    return head;
}
 
// Driver code
int main()
{
    /* Tree:
         10
        /  \
      15    2
     /  \
    1    5
*/
    treeNode* root = new treeNode(10);
    root->left = new treeNode(15);
    root->right = new treeNode(2);
    root->left->left = new treeNode(1);
    root->left->right = new treeNode(5);
 
    Node* head = sortedList(NULL, root);
    print(head);
 
    return 0;
}

Java




// Java implementation of the approach
import java.util.*;
 
class GFG
{
 
// A linked list node
static class Node
{
    int data;
    Node next;
    Node(int data)
    {
        this.data = data;
        this.next = null;
    }
};
 
// A binary tree node
static class treeNode
{
    int data;
    treeNode left;
    treeNode right;
    treeNode(int data)
    {
        this.data = data;
        this.left = null;
        this.right = null;
    }
};
 
// Function to print the linked list
static void print(Node head)
{
    if (head == null)
    {
        return;
    }
    Node temp = head;
    while (temp != null)
    {
        System.out.print(temp.data + " ");
        temp = temp.next;
    }
}
 
// Function to create Linked list from given binary tree
static Node sortedList(Node head, treeNode root)
{
    // return head if root is null
    if (root == null)
    {
        return head;
    }
 
    // First make the sorted linked list
    // of the left sub-tree
    head = sortedList(head, root.left);
    Node newNode = new Node(root.data);
    Node temp = head;
    Node prev = null;
 
    // If linked list is empty add the
    // node to the head
    if (temp == null)
    {
        head = newNode;
    }
    else
    {
 
        // Find the correct position of the node
        // in the given linked list
        while (temp != null)
        {
            if (temp.data > root.data)
            {
                break;
            }
            else
            {
                prev = temp;
                temp = temp.next;
            }
        }
 
        // Given node is to be attached
        // at the end of the list
        if (temp == null)
        {
            prev.next = newNode;
        }
        else
        {
 
            // Given node is to be attached
            // at the head of the list
            if (prev == null)
            {
                newNode.next = temp;
                head = newNode;
            }
            else
            {
 
                // Insertion in between the list
                newNode.next = temp;
                prev.next = newNode;
            }
        }
    }
 
    // Now add the nodes of the right sub-tree
    // to the sorted linked list
    head = sortedList(head, root.right);
    return head;
}
 
// Driver code
public static void main(String[] args)
{
    /* Tree:
        10
        / \
    15 2
    / \
    1 5
*/
    treeNode root = new treeNode(10);
    root.left = new treeNode(15);
    root.right = new treeNode(2);
    root.left.left = new treeNode(1);
    root.left.right = new treeNode(5);
 
    Node head = sortedList(null, root);
    print(head);
}
}
 
// This code is contributed by 29AjayKumar

C#




// C# implementation of the approach
using System;
 
class GFG
{
 
// A linked list node
class Node
{
    public int data;
    public Node next;
    public Node(int data)
    {
        this.data = data;
        this.next = null;
    }
};
 
// A binary tree node
class treeNode
{
    public int data;
    public treeNode left;
    public treeNode right;
    public treeNode(int data)
    {
        this.data = data;
        this.left = null;
        this.right = null;
    }
};
 
// Function to print the linked list
static void print(Node head)
{
    if (head == null)
    {
        return;
    }
    Node temp = head;
    while (temp != null)
    {
        Console.Write(temp.data + " ");
        temp = temp.next;
    }
}
 
// Function to create Linked list
// from given binary tree
static Node sortedList(Node head, treeNode root)
{
    // return head if root is null
    if (root == null)
    {
        return head;
    }
 
    // First make the sorted linked list
    // of the left sub-tree
    head = sortedList(head, root.left);
    Node newNode = new Node(root.data);
    Node temp = head;
    Node prev = null;
 
    // If linked list is empty add the
    // node to the head
    if (temp == null)
    {
        head = newNode;
    }
    else
    {
 
        // Find the correct position of the node
        // in the given linked list
        while (temp != null)
        {
            if (temp.data > root.data)
            {
                break;
            }
            else
            {
                prev = temp;
                temp = temp.next;
            }
        }
 
        // Given node is to be attached
        // at the end of the list
        if (temp == null)
        {
            prev.next = newNode;
        }
        else
        {
 
            // Given node is to be attached
            // at the head of the list
            if (prev == null)
            {
                newNode.next = temp;
                head = newNode;
            }
            else
            {
 
                // Insertion in between the list
                newNode.next = temp;
                prev.next = newNode;
            }
        }
    }
 
    // Now add the nodes of the right sub-tree
    // to the sorted linked list
    head = sortedList(head, root.right);
    return head;
}
 
// Driver code
public static void Main(String[] args)
{
    /* Tree:
        10
        / \
    15 2
    / \
    1 5
    */
    treeNode root = new treeNode(10);
    root.left = new treeNode(15);
    root.right = new treeNode(2);
    root.left.left = new treeNode(1);
    root.left.right = new treeNode(5);
 
    Node head = sortedList(null, root);
    print(head);
}
}
 
// This code is contributed by PrinciRaj1992

Python3




# Python3 implementation of the approach
 
# A linked list node
class Node:
    def __init__(self, data = 0):
        self.data = data
        self.next = None
 
# A binary tree node
class treeNode:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
     
# Function to print the linked list
def print_(head):
 
    if (head == None):
        return
 
    temp = head
    while (temp != None):
        print ( temp.data, end = " " )
        temp = temp.next
     
# Function to create Linked list from given binary tree
def sortedList( head, root):
 
    # return head if root is None
    if (root == None) :
     
        return head
 
    # First make the sorted linked list
    # of the left sub-tree
    head = sortedList(head, root.left)
    newNode = Node(root.data)
    temp = head
    prev = None
 
    # If linked list is empty add the
    # node to the head
    if (temp == None) :
        head = newNode
     
    else:
 
        # Find the correct position of the node
        # in the given linked list
        while (temp != None):
         
            if (temp.data > root.data) :
                break
             
            else:
                prev = temp
                temp = temp.next
 
        # Given node is to be attached
        # at the end of the list
        if (temp == None):
            prev.next = newNode
         
        else:
             
            # Given node is to be attached
            # at the head of the list
            if (prev == None) :
                newNode.next = temp
                head = newNode
             
            else:
 
                # Insertion in between the list
                newNode.next = temp
                prev.next = newNode
             
    # Now add the nodes of the right sub-tree
    # to the sorted linked list
    head = sortedList(head, root.right)
    return head
 
# Driver code
 
# Tree:
# 10
# / \
# 15 2
# / \
#1 5
 
root = treeNode(10)
root.left = treeNode(15)
root.right = treeNode(2)
root.left.left = treeNode(1)
root.left.right = treeNode(5)
 
head = sortedList(None, root)
 
print_(head)
 
# This code is contributed by Arnab Kundu

Javascript




<script>
 
// JavaScript implementation of the approach
 
// A linked list node
class Node {
 
    constructor(data)
    {
        this.data = data;
        this.next = null;
    }
};
 
// A binary tree node
class treeNode {
 
    constructor(data)
    {
        this.data = data;
        this.left = null;
        this.right = null;
    }
};
 
// Function to print the linked list
function print(head)
{
    if (head == null) {
        return;
    }
    var temp = head;
    while (temp != null) {
        document.write( temp.data + " ");
        temp = temp.next;
    }
}
 
// Function to create Linked list from given binary tree
function sortedList(head, root)
{
    // return head if root is null
    if (root == null) {
        return head;
    }
 
    // First make the sorted linked list
    // of the left sub-tree
    head = sortedList(head, root.left);
    var newNode = new Node(root.data);
    var temp = head;
    var prev = null;
 
    // If linked list is empty add the
    // node to the head
    if (temp == null) {
        head = newNode;
    }
    else {
 
        // Find the correct position of the node
        // in the given linked list
        while (temp != null) {
            if (temp.data > root.data) {
                break;
            }
            else {
                prev = temp;
                temp = temp.next;
            }
        }
 
        // Given node is to be attached
        // at the end of the list
        if (temp == null) {
            prev.next = newNode;
        }
        else {
 
            // Given node is to be attached
            // at the head of the list
            if (prev == null) {
                newNode.next = temp;
                head = newNode;
            }
            else {
 
                // Insertion in between the list
                newNode.next = temp;
                prev.next = newNode;
            }
        }
    }
 
    // Now add the nodes of the right sub-tree
    // to the sorted linked list
    head = sortedList(head, root.right);
    return head;
}
 
// Driver code
 
    /* Tree:
         10
        /  \
      15    2
     /  \
    1    5
*/
var root = new treeNode(10);
root.left = new treeNode(15);
root.right = new treeNode(2);
root.left.left = new treeNode(1);
root.left.right = new treeNode(5);
var head = sortedList(null, root);
print(head);
 
 
</script>
Output: 
1 2 5 10 15

 

Time Complexity: O(n2)
 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :