×

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

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.

Serialize and Deserialize Binary Trees

In order to save a tree in a file that can later be restored, serialisation is used. The tree's structure must be preserved. Deserialization involves reading a tree from a...

4 minutes read.

Difference between Stack and Queue

In this article, we will learn about the major differences between Stack and Queue data structures. What is a stack? Stack – A stack is an abstract data structure defined as the...

3 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.

Applications of Different Linked Lists in Data Structure

What is a Linked list? A linked list is a data structure that consists of a sequence of elements, where each containing a reference or ("link") to the next element in...

5 minutes read.

Splay Tree

Splay Tree A splay tree is a self-balanced or self-adjusted binary search tree. We can say, Splay Tree is used in some cases where some elements or data are accessed more...

8 minutes read.

Digital Search Tree in Data Structures

What is a digital search Tree in Data Structures? The Digital search tree is known for its application and diversity in the way it has impacted our world in the field...

3 minutes read.

Box Stacking Problem

Stacking of boxes depending on their base You have been given n different boxes. These boxes will have different heights, widths, and depths. You have to stack all these boxes in...

4 minutes read.

Symmetric binary tree

Implementation // writing a C++ program to check whether a given binary tree is symmetric or not. #include <bits/stdc++.h> using namespace std; // creating a binary tree node. struct __Nod { int ky; struct __Nod *Lft, *Rt; }; //...

4 minutes read.

A Full Binary Tree with n Nodes

Implementation // Writing the implementation of the above approach in C++ #include <bits/stdc++.h> using namespace std; // We are creating a class that will create a node and its left and right children.  struct __nod...

12 minutes read.

Binary tree insertion

As we all know, a binary tree has a maximum of two children and helps us manage the info correctly. Here the name of the tree itself portrays the mechanism...

4 minutes read.

Breadth First Search

Breadth First Search Breadth first search is a graph traversing algorithm. In this, we start traversing from the source node or any selected node and traverse the graph layer by layer....

6 minutes read.

Intersection Point in Y Shaped Linked Lists in Java

Intersection Point in Y Shaped Linked Lists in Java In this article, we are going to see how to find the intersection point in a Y-shaped linked list. Method 1: We need to...

4 minutes read.

Finding the Sum of All Paths in a Binary Tree

Implementation // Writing the C++ program to implement the below approach.  #include <bits/stdc++.h> using namespace std; // creating the new tree node structure. struct Tree__nod { int val; Tree__nod *Lft, *Rt; }; // creating a new function that will...

8 minutes read.

Binary search tree traversal in-order pre-order post-order examples

A binary search tree is a type of non-linear tree in which the tree contains at least two nods. It is called binary because of its nature that states bi...

8 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.

Trie data structure

Trie data structure The term “trie” comes from the word “retrieval” which means getting information. The trie data structure is a sorted extension of tree-based data structure. The trie data structure...

5 minutes read.

Minimum Spanning Tree

Before getting to know about the minimum spanning tree, we should first discuss about what is a spanning tree. A spanning tree is basically a sub or minimized graph that...

7 minutes read.

Queue Data Structure

Queue in DS: The queue is a non-primitive and linear data structure. It works on the principle of FIFO (First In First Out). That is, the element that is added...

4 minutes read.

Queue Implementation using stacks Data Structure

Queue Implementation using stacks In this problem, we have stack data structure which supports only push() and pop() operations. We are required to implement a queue data structure using the instances...

4 minutes read.