Open In App

# Create a sorted linked list from the given Binary Tree

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 ``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

 ``

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``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<data<<``" "``;``        ``temp = temp->next;``    ``}``    ``cout< &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

 `import` `java.util.*;` `// a linked list node``class` `LNode{``    ``int` `data;``    ``LNode next;``    ``LNode(``int` `data){``        ``this``.data = data;``        ``this``.next = ``null``;``    ``}``}` `// a binary tree node``class` `TNode{``    ``int` `data;``    ``TNode left;``    ``TNode right;``    ``TNode(``int` `data){``        ``this``.data = data;``        ``this``.left = ``null``;``        ``this``.right = ``null``;``    ``}``}` `// main class``class` `Main{``    ``// function to print the linked list``    ``static` `void` `printList(LNode head){``        ``if``(head == ``null``) ``return``;``        ``LNode temp = head;``        ``while``(temp != ``null``){``            ``System.out.print(temp.data+``" "``);``            ``temp = temp.next;``        ``}``        ``System.out.println();``    ``}` `    ``// function to store in Inorder fashion``    ``static` `void` `inOrder(TNode root, ArrayList vec){``        ``if``(root == ``null``) ``return``;``        ``inOrder(root.left, vec);``        ``vec.add(root.data);``        ``inOrder(root.right, vec);``    ``}` `    ``// function to create sorted linked list from given binary tree``    ``static` `LNode sortedList(TNode root){``        ``// initializing vector to store the elements``        ``ArrayList vec = ``new` `ArrayList();``        ``inOrder(root, vec);``        ``Collections.sort(vec);``        ``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``    ``public` `static` `void` `main(String[] args){``        ``/* 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);``    ``}``}`

## Python

 `# Python program for the above approach``# a linked list node``class` `LNode:``    ``def` `__init__(``self``, data):``        ``self``.data ``=` `data``        ``self``.``next` `=` `None``    `  `# a binary tree node``class` `TNode:``    ``def` `__init__(``self``, data):``        ``self``.data ``=` `data``        ``self``.left ``=` `None``        ``self``.right ``=` `None``    `  `# function to print the linked list``def` `printList(head):``    ``if``(head ``is` `None``):``        ``return``    ``temp ``=` `head``    ``while``(temp ``is` `not` `None``):``        ``print``(temp.data)``        ``temp ``=` `temp.``next``    ` `    ` `# function to store in Inorder fashion``def` `inOrder(root, vec):``    ``if``(root ``is` `None``):``        ``return``    ``inOrder(root.left, vec)``    ``vec.append(root.data)``    ``inOrder(root.right, vec)``    `  `# function to create sorted linked list from given binary tree``def` `sortedList(root):``    ``# initialize vector to store the elements``    ``vec ``=` `[]``    ``inOrder(root, vec)``    ``vec.sort()``    ``head ``=` `LNode(``-``1``)``    ``temp ``=` `head``    ``for` `i ``in` `vec:``        ``temp.``next` `=` `LNode(i)``        ``temp ``=` `temp.``next``    ``head ``=` `head.``next``    ``return` `head``    `  `# driver code to test above function``root ``=` `TNode(``10``)``root.left ``=` `TNode(``15``)``root.right ``=` `TNode(``2``)``root.left.left ``=` `TNode(``1``)``root.left.right ``=` `TNode(``5``)` `head ``=` `sortedList(root)``printList(head)`

## C#

 `// C# Program for the above approach``using` `System;``using` `System.Collections.Generic;` `// a linked list node``public` `class` `LNode{``    ``public` `int` `data;``    ``public` `LNode next;``    ``public` `LNode(``int` `item){``        ``data = item;``        ``next = ``null``;``    ``}``}` `// a binary tree node``public` `class` `TNode{``    ``public` `int` `data;``    ``public` `TNode left, right;``    ``public` `TNode(``int` `item){``        ``data = item;``        ``left = right = ``null``;``    ``}``}` `class` `GFG{``    ``// function to print the linked list``    ``static` `void` `printList(LNode head){``        ``if``(head == ``null``) ``return``;``        ``LNode temp = head;``        ``while``(temp != ``null``){``            ``Console.Write(temp.data + ``" "``);``            ``temp = temp.next;``        ``}``    ``}``    ` `    ``// function to store in Inorder fashion``    ``static` `void` `inOrder(TNode root, List<``int``> vec){``        ``if``(root == ``null``) ``return``;``        ``inOrder(root.left, vec);``        ``vec.Add(root.data);``        ``inOrder(root.right, vec);``    ``}``    ` `    ``// function to create sorted linked list from given binary tree``    ``static` `LNode sortedList(TNode root){``        ``// initializing vector to store the elements``        ``List<``int``> vec = ``new` `List<``int``>();``        ``inOrder(root, vec);``        ``vec.Sort();``        ``LNode head = ``new` `LNode(-1);``        ``LNode temp = head;``        ``for``(``int` `i = 0; i

## Javascript

 `// JavaScript program for the above approach``// a linked list node``class LNode{``    ``constructor(data){``        ``this``.data = data;``        ``this``.next = ``null``;``    ``}``}`  `// a binary tree node``class TNode{``    ``constructor(data){``        ``this``.data = data;``        ``this``.left = ``null``;``        ``this``.right = ``null``;``    ``}``}` `// function to print the linked list``function` `printList(head){``    ``if``(head == ``null``) ``return``;``    ``let temp = head;``    ``while``(temp != ``null``){``        ``console.log(temp.data + ``" "``);``        ``temp = temp.next;``    ``}``    ``console.log(``" "``);``}` `// function to store the inorder fashion``function` `inOrder(root, vec){``    ``if``(root == ``null``) ``return``;``    ``inOrder(root.left, vec);``    ``vec.push(root.data);``    ``inOrder(root.right, vec);``}` `// function to create sorted linked list from given binary tree``function` `sortedList(root){``    ``// initializing vector to store the elements``    ``let vec = [];``    ``inOrder(root, vec);``    ``vec.sort(``function``(a,b){``return` `a-b});``    ``let head = ``new` `LNode(-1);``    ``let temp = head;``    ``for``(let i = 0; i

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.