Create a sorted linked list from the given Binary Tree - GeeksforGeeks

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++
Java
C#
Python3
Javascript
// C++ implementation of the approach#include <iostream>using namespace std; // A linked list nodeclass Node {public:    int data;    Node* next;    Node(int data)    {        this->data = data;        this->next = NULL;    }}; // A binary tree nodeclass 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 listvoid 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 treeNode* 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 codeint 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 implementation of the approachimport java.util.*; class GFG{ // A linked list nodestatic class Node{    int data;    Node next;    Node(int data)    {        this.data = data;        this.next = null;    }}; // A binary tree nodestatic 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 liststatic 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 treestatic 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 codepublic 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# implementation of the approachusing System; class GFG{ // A linked list nodeclass Node{    public int data;    public Node next;    public Node(int data)    {        this.data = data;        this.next = null;    }}; // A binary tree nodeclass 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 liststatic 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 treestatic 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 codepublic 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 implementation of the approach # A linked list nodeclass Node:    def __init__(self, data = 0):        self.data = data        self.next = None # A binary tree nodeclass treeNode:    def __init__(self, data):        self.data = data        self.left = None        self.right = None     # Function to print the linked listdef 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 treedef 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
<script> // JavaScript implementation of the approach // A linked list nodeclass Node {     constructor(data)    {        this.data = data;        this.next = null;    }}; // A binary tree nodeclass treeNode {     constructor(data)    {        this.data = data;        this.left = null;        this.right = null;    }}; // Function to print the linked listfunction 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 treefunction 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>
1 2 5 10 15
 
Time Complexity: O(n2) 
29AjayKumar
princiraj1992
andrew1234
itsok
Linked List
Tree
Linked List
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Circular Linked List | Set 2 (Traversal)
Swap nodes in a linked list without swapping data
Circular Singly Linked List | Insertion
Given a linked list which is sorted, how will you insert in sorted way
Real-time application of Data Structures
Tree Traversals (Inorder, Preorder and Postorder)
AVL Tree | Set 1 (Insertion)
Binary Tree | Set 1 (Introduction)
Level Order Binary Tree Traversal
Binary Tree | Set 3 (Types of Binary Tree)