×

Convert binary tree to a doubly linked list

Implementation

//creating a C++ program for the transition of a binary tree into a linked list.
#include <iostream>
using namespace std;


/* Firstly, let’s create a binary tree that will help us in setting the records and will also contain left and right pointers.
*/
struct nod {
	int record;
	nod* Lft;
	nod* Rt;
};


// Creating a very simple and basic recursive function that will change the given binary tree into a doubly linked list root which can be the root of the binary tree.
// head --> Pointer to head node of created doubly-linked
// list
void BinaryTree2DoubleLinkedList(nod* root, nod** head)
{
	if (root == NILL)
		return;


	// we have to put the lastly traversed nod as NILL and initialize it as well
	// This will turn into the static function, which will contain the same value as in all the recursive calls we already have. 
	static nod* pre= NILL;


	// we will have to convert the left subtree recursively.
	BinaryTree2DoubleLinkedList(root->Lft, head);


	// we will now have to change this node into something else.
	if (pre== NILL)
		*head = root;
	else {
		root->Lft = prev;
		prev->Rt = root;
	}
	pre= root;


	// finally, we have to change the right subtree.
	BinaryTree2DoubleLinkedList(root->Rt, head);
}


/* This is a new function called the helper which will hold the responsibility of attaching a new node to the given data and emptying the left and right pointers.
*/
nod* newNod(int record)
{
	nod* new_nod = new nod;
	new_nod->record = record;
	new_nod->Lft = new_nod->Rt = NILL;
	return (new_nod);
}


/* creating a function that will help us in printing all the nodes of a double-linked list. */
void printList(nod* nod)
{
	while (nod != NILL) {
		cout << nod->record << " ";
		nod = nod->Rt;
	}
}


/* writing the main code, which will help us in testing. */
int main()
{
	// Let us create the tree shown in the above diagram
	nod* root = newNod(10);
	root->Lft = newNod(12);
	root->Rt = newNod(15);
	root->Lft->Lft = newNod(25);
	root->Lft->Rt = newNod(30);
	root->Rt->Lft = newNod(36);


	// changing the above into doubly linked lists.
	nod* head = NILL;
	BinaryTree2DoubleLinkedList(root, &head);


	// Print the converted list
	printList(head);


	return 0;
}

Output:

Convert binary tree to a doubly linked list

Example 2)

//creating a C program for the transition of a binary tree into a linked list. 
# includes <stdio.h>
#include <stdlib.h>
/*creating a binary tree that will contain records and will also have some left and right pointers. 
*/
typedef struct nod {
	int record;
	struct nod* Lft;
	struct nod* Rt;
} nod;
// Creating a very simple and basic recursive function that will change the given binary tree into a doubly linked list root which can be the root of the binary tree.
// head --> Pointer to head nod of created doubly-linked
// list
void BinaryTree2DoubleLinkedList(nod* root, nod** head)
{
	if (root == NILL)
		return;
// we have to put the lastly traversed nod as NILL and initialize it as well
		// This will turn into the static function, which will contain the same value as in all the recursive calls we already have. 
	static nod* pre= NILL;


	// we will have to convert the left subtree in a recursive manner.
	BinaryTree2DoubleLinkedList(root->Lft, head);
// we will now have to change this node into something else.
	if (pre== NILL)
		*head = root;
	else {
		root->Lft = prev;
		prev->Rt = root;
	}
	pre= root;


	// finally, we have to change the right subtree.
	BinaryTree2DoubleLinkedList(root->Rt, head);
}
/* This is a new function called the helper which will hold the responsibility of attaching a new node to the given data and emptying the left and right pointers.
*/
nod* newNod(int record)
{
	nod* new_nod = (nod*)malloc(sizeof(nod));
	new_nod->record = record;
	new_nod->Lft = new_nod->Rt = NILL;
	return (new_nod);
}
/* creating a function that will help us in printing all the nodes of a double-linked list. */
void printList(nod* nod)
{
	while (nod != NILL) {
		printf("%d ", nod->record);
		nod = nod->Rt;
	}
}
/* writing the main code, which will help us in testing. */
int main()
{
	nod* root = newNod(10);
	root->Lft = newNod(12);
	root->Rt = newNod(15);
	root->Lft->Lft = newNod(25);
	root->Lft->Rt = newNod(30);
	root->Rt->Lft = newNod(36);


		// changing the above into doubly linked lists.
	nod* head = NILL;
	BinaryTree2DoubleLinkedList(root, &head);


	// Print the converted list
	printList(head);


	return 0;
}

Output:

Convert binary tree to a doubly linked list

Example 3)

// creating a Java program for the transition of a binary tree into a linked list.
// A binary tree nod has the record, left pointers, and right pointers
class Nod
{
	int record;
	Nod Lft, Rt;


	public Nod(int record)
	{
		this.record = record;
		Lft = Rt = NILL;
	}
}


class BinaryTree
{
	Nod root;
	
	// head --> Pointer to head nod of created doubly linked list
	Nod head;
	
	// Initialize previously visited nod as NILL. This is
	// static so that the same value is accessible in all-recursive
	// calls
	static Nod pre= NILL;


	// A simple recursive function to convert a given Binary tree
	// to Doubly Linked List
	// root --> Root of Binary Tree
	void BinaryTree2DoubleLinkedList(Nod root)
	{
		// Base case
		if (root == NILL)
			return;


		// Recursively convert Left subtree
		BinaryTree2DoubleLinkedList(root.Lft);


		// Now convert this nod
		if (pre== NILL)
			head = root;
		else
		{
			root.Lft = prev;
			prev.Rt = root;
		}
		pre= root;


		// Finally, convert the right subtree
		BinaryTree2DoubleLinkedList(root.Rt);
	}


	/* Function to print nods in a given doubly linked list */
	void printList(Nod nod)
	{
		while (nod != NILL)
		{
			System.out.print(nod.record + " ");
			nod = nod.Rt;
		}
	}


	// Driver program to test the above functions
	public static void main(String[] args)
	{
		// Let us create the tree as shown in the above diagram
		BinaryTree tree = new BinaryTree();
		tree.root = new Nod(10);
		tree.root.Lft = new Nod(12);
		tree.root.Rt = new Nod(15);
		tree.root.Lft.Lft = new Nod(25);
		tree.root.Lft.Rt = new Nod(30);
		tree.root.Rt.Lft = new Nod(36);


		// changing the above into doubly linked lists.
		Tree.BinaryTree2DoubleLinkedList(tree.root);
		
		// Print the converted List
		tree.printList(tree.head);


	}
}

Output:

Convert binary tree to a doubly linked list

Related Topics

Given a Perfect Binary Tree, Reverse Alternate Levels

Implementation //writing a program in C++ language to see how to approach it. #include <bits/stdc++.h> using namespace std; // creating a tree node. struct Nod { char ky; struct Nod *Lft, *Rt; }; // creating a new utility function...

9 minutes read.

Does Overloading Work with Inheritance

This is a question that occasionally comes to many programmers. Who are curious to know more now has a complete explanation and a solution through this tutorial! Inheritance: The functions of...

3 minutes read.

Delete nodes from the linked list which have a greater value on the right side

Delete nodes from the linked list which have a greater value on the right side In this problem, we have given a singly linked list, and we need to remove all...

3 minutes read.

Bubble Sort vs Heap Sort

In this article, we are going to compare the two most common sorting techniques, Bubble Sort and Heap sort. Before discussing their differences, let us first discuss the idea of...

7 minutes read.

Bubble Sort in Data Structures

Bubble Sort in C++ The bubble sort algorithm analyses two adjacent elements and swaps them until they are no longer in the desired order. Each iteration moves each member of the array...

4 minutes read.

B+ Tree in Data Structure

A B-Tree extension called B+ Tree, which enables effective search, insertion, and deletion operations. Both Records and keys can be stored in internal and leaf nodes in a B tree. Contrarily,...

4 minutes read.

Pairwise swap elements of a given linked list

Pairwise swap elements of a given linked list In this problem, we have given a linked list, and we need to pairwise swap elements of the given linked list. Example:                                     Input:1 ->3...

4 minutes read.

Number of visible boxes putting one inside another

You have given one array, which consists of values which represent the sizes of different boxes. We can put one box inside another if the size of the outside box...

3 minutes read.

Quick Sort vs Merge Sort

In this article, we will take an overview of Quick Sort and Merge Sort and then discuss the differences between them. What is Quick Sort? Quick Sort – The idea behind the...

7 minutes read.

Given a Binary Tree Print the Shortest Path

Implementation // Writing a program in C++ to find the shortest between the nodes i and j.  #include <bits/stdc++.h> using namespace std; // the given function will print the path between nodes i and...

7 minutes read.

Find all possible words from board

We have been given a dictionary of words and a board of characters from which we can form strings. Now, we have to check if the string is present in...

5 minutes read.

Winner tree in Data Structures

Tree Data structure A tree is a hierarchical and non-linear data structure with nodes. Each node in the Tree contains a message value and stores the name passed to another ("child")...

6 minutes read.

Segregate Even and Odd nodes in a Linked List

Segregate even and odd nodes in a Linked List In this problem, we have given a linked list with integer numbers. We need to modify the given linked list in such...

4 minutes read.

Introduction to 1D-Arrays

One Dimensional Array Technical Definitions The simplest version of an Array is a One-Dimensional Array, in which the items are stored linearly and may be accessed individually by supplying the index value...

6 minutes read.

Tim Sort

Tim Sort is a mixture stable arranging calculation that exploits normal examples in information, and uses a mix of an improved Merge sort and Binary Insertion sort alongside an interior...

6 minutes read.

Hashing

Hashing: Hashing is a process in which a large amount of data is mapped to a small table with the help of hashing function. It is a searching technique. Hash table We...

4 minutes read.

Convert Sorted List to Binary Search Tree

Implementation // creating the C++ implementation of the following approach: - #include <bits/stdc++.h> using namespace std; /* Create the link list node and see its implementation. */ class L__Nod { public: int record; L__Nod* next; }; /* constructing a new binary...

15 minutes read.

Given a Binary Tree Check the Zig-Zag Traversal

Implementation // The C++ implementation of the zig-zag traversal method in the O(n) time.  #include <iostream> #include <stack> using namespace std; // creating a binary tree node. struct __nod { int record; struct __nod *Lft, *Rt; }; // creating a...

4 minutes read.

Implementation of stack

Implementation of stack: The stack can be implemented in two ways: using array and using a linked list. The pop and push operations in the array are simpler than the...

3 minutes read.

Bucket Sort

Bucket Sort: In the sorting algorithm, we create buckets and put elements into them. We can apply some sorting algorithm (insertion sort) to sort the elements in each bucket. Finally,...

4 minutes read.