Open In App

Create a sorted linked list from the given Binary Tree

Last Updated : 14 Apr, 2023
Comments
Improve
Suggest changes
84 Likes
Like
Report

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

C#

Python3

Javascript

Output

1 2 5 10 15 

Time Complexity: O(n2)

Auxiliary Space: O(n)

Another Approach(Using extra space):
Follow the below steps to solve the problem:
1) Create an array to store the all elements of given binary tree.
2) Sort the given array in O(NlogN) time and then traverse the sorted array.
3) While traversing the sorted array then create given linked list for each element.
4) print the created sorted linked list.

Below is the implementation of above approach:

C++




// C++ program for the above approach
#include<bits/stdc++.h>
using namespace std;
 
// a linked list node
struct LNode{
    int data;
    LNode* next;
    LNode(int data){
        this->data = data;
        this->next = NULL;
    }
};
 
// a binary tree node
struct TNode{
    int data;
    TNode* left;
    TNode* right;
    TNode(int data){
        this->data = data;
        this->left = NULL;
        this->right = NULL;
    }
};
 
// function to print the linked list
void printList(LNode* head){
    if(head == NULL) return;
    LNode* temp = head;
    while(temp != NULL){
        cout<<temp->data<<" ";
        temp = temp->next;
    }
    cout<<endl;
}
 
// function to store in Inorder fashion
void inOrder(TNode* root, vector<int> &vec){
    if(root == NULL) return;
    inOrder(root->left, vec);
    vec.push_back(root->data);
    inOrder(root->right, vec);
}
 
// function to create sorted linked list from given binary tree
LNode* sortedList(TNode* root){
    // initializing vector to store the elements
    vector<int> vec;
    inOrder(root, vec);
    sort(vec.begin(), vec.end());
    LNode* head = new LNode(-1);
    LNode* temp = head;
    for(int i : vec){
        temp->next = new LNode(i);
        temp = temp->next;
    }
    head = head->next;
    return head;
}
 
// driver code to test above functions
int main(){
    /* Tree:
         10
        /  \
      15    2
     /  \
    1    5
    */
    TNode* root = new TNode(10);
    root->left = new TNode(15);
    root->right = new TNode(2);
    root->left->left = new TNode(1);
    root->left->right = new TNode(5);
     
    LNode* head = sortedList(root);
    printList(head);
    return 0;
}
// THIS CODE IS CONTRIBUTED BY YASH AGARWAL(YASHAGARWAL2852002)


Java

Python

C#

Javascript

Output

1 2 5 10 15 

Time Complexity: O(N) where N is the number of nodes in given binary tree.
Auxiliary Space: O(N) due to extra space.



Next Article
Article Tags :
Practice Tags :

Similar Reads