×

Binary Tree to Doubly Linked List

Binary Tree to Doubly Linked List

This article will explain how to convert the given binary tree into a Doubly Linked List. The left and right pointers in tree nodes are to be used as previous and next pointers in the resultant doubly linked list. The order of nodes in the doubly linked list must be the same as inorder of the given binary tree. The first node of inorder traversal must be the head node of the doubly linked list.

Method:

In this method, we will traverse the binary tree and store its inorder representation in the arraylist. After this, we will make the doubly linked list by using that array list.

Algorithm of inorder traversal:

        void inorder(Node temp)
        {
                         if(temp == null)
                                     return;
                         inorder(temp.left);
                         l.add(temp.data);       
                         inorder(temp.right);    
        } 

Algorithm of adding a node in the linked list:

 void add(int data)
      {
             if(head == null)
         {
                         head  =  new Node(data);
                         return;
         }
             else
             {
                         Node temp  =  head;
                         while(temp.right !=  null)
                         {
                                     temp = temp.right;
                         }
                         Node t = temp;
                         temp.right = new Node(data);
                         temp = temp.right;
                         temp.left = t;
             }
     } 

Source code for in-place conversion of Binary Tree to Doubly Linked List using Java programming:

 import java.util.*;
 public class BinaryTree
 {
             static Node root, head;
             // Arraylist for storing element of binary tree
            ArrayList<Integer> l = new ArrayList<>();
            // Structure of the node
             static class Node
             {
                         int data;
                         Node left = null;
                         Node right = null;
                         Node(int data)
                         {
                                     this.data = data;
                         }
             }
      // Method for inorder traversal of the binary tree
        void inorder(Node temp)
        {
                         if(temp == null)
                                     return;
                         inorder(temp.left);
                         l.add(temp.data);       
                         inorder(temp.right);    
        }
    // Method for adding a node in the doubly linked list
      void add(int data)
      {
             if(head == null)
         {
                         head  =  new Node(data);
                         return;
         }
             else
             {
                         Node temp  =  head;
                         while(temp.right !=  null)
                         {
                                     temp = temp.right;
                         }
                         Node t = temp;
                         temp.right = new Node(data);
                         temp = temp.right;
                         temp.left = t;
             }
     }
    // Method to convert the binary tree to the doubly linked list
      void binaryToDoubly()
      {
                         inorder(root);
                         int i = 0;
                         while(i < l.size())
                         {
                                     add(l.get(i));
                                     i++;
                         }
      }
   // Method for print the elements of doubly linked list
      void printList(Node temp)
     {
         while (temp != null)
         {
             System.out.print(temp.data + " ");
             temp = temp.right;
         }
     }
  // Driver method of this program
     public static void main(String args[])
    {
          BinaryTree ob = new BinaryTree ();
          ob.root = new Node(9);
          ob.root.left = new Node(13);
          ob.root.right = new Node(16);
          ob.root.left.left = new Node(23);
          ob.root.left.right = new Node(35);
          ob.root.right.left = new Node(39);         
          ob.binaryToDoubly();
          System.out.println("Doubly Linked list:");
          ob.printList(head);
    }
 } 

Output:

Binary Tree to Doubly Linked List

Time Complexity: This method works on simple inorder traversal, so the time complexity of this method is O(n), where n is the number of nodes in a given binary tree.

Space Complexity: The space complexity of this method is O(n) because we use extra space for storing the elements of the binary tree.


Related Topics

Linear Queue VS Circular Queue

What is Queue? A queue is one of the important linear data structures extensively used in various computer applications. It is based on the FIFO (First In First Out) principle. It...

9 minutes read.

Hashing and its Applications

Hashing Hashing refers to transforming plain text data in such a way that even if it is leaked for some reason, no one would be able to make sense of it....

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

Reverse a Linked List in groups of given size

Reverse a Linked List in groups of given size This article will explain how to reverse a linked list in groups of given size. Here we have given a linked list...

2 minutes read.

Deletion in B+ Tree

Make a search for the leaf node that containing the key value by taking the value in a key value. If the required key value is found, then it will remove...

6 minutes read.

B Tree in Data Structure

Data management is called database management. A data model is a system that stores, manages, and optimizes computer resources. Data processing is not just about data storage. Almost every app...

9 minutes read.

Data Structure Prefix to Postfix Conversion

Prefix to Postfix Conversion Prefix: As the name suggests if the operator placed before the operands called the prefix expression.  The form of prefix expression is (operator, operand1, operand2). Example:  *+EF-GH (Infix:...

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

Introduction to Arrays

What exactly is an array? A group of related data pieces stored in contiguous memory regions is referred to as an array. It is the most basic data structure in which...

5 minutes read.

Linked List Data Structure

Linked list in DS: The linked list is a non-primitive and linear data structure. It is a list of a particular type of data element that is connected to each...

3 minutes read.

Types of Linked list

Single linked list  A single linked list is a linked list in which all nodes are connected with each other in sequence. Each node of a singly linked list has two...

7 minutes read.

Given a Binary Tree, find its Minimum Depth

Implementation // Creating a C++ program or implementation to search and explore the minimum depth of a given binary tree.  #include<bits/stdc++.h> using namespace std; // Creating a new binary tree node struct __nod { int record; struct __nod*...

5 minutes read.

Linear vs Circular Queue: Data Structure

Difference Between Linear and Circular Queue What is Linear Queue? A linear queue is linear data structure which works on first in first out principle. We can say a linear queue is...

3 minutes read.

Delete a Node without head pointer from the linked list

Delete a Node without head pointer from the linked list This article will explain how to delete a node without a head pointer from the linked list. We have given a...

2 minutes read.

Operations on Queue in Data Structures

A queue is a linear structure where operations are done in a specific sequence. Queues are abstract data structures that are comparable to Stacks. A queue, unlike a stack, is...

8 minutes read.

Difference between B-tree and Binary Tree

What is B-TREE? The nodes of B-tree are sorted during in-order traversal, and it is called self-balancing tree. A node in a B-tree can have more than two offspring, in contrast...

3 minutes read.

Asynchronous advantage actor-critic (A3C) Algorithm

The Asynchronous advantage actor-critic (A3C) Algorithm is one of the latest algorithms developed by the Artificial Intelligence division, Deep Mind at Google. It is used for the Deep Reinforcement Learning...

3 minutes read.

Operations on 2D-Arrays

Two Dimensional Array Operations Adding Elements to Two-D Arrays We must put data in both rows and columns when inserting items in 2-D Arrays. As a result, we employ the idea of...

10 minutes read.

Delete N nodes after M nodes of a linked list

Delete N nodes after M nodes of a linked list In this problem, we have given a linked list and two integers M and N. We need to traverse the linked...

3 minutes read.

Semi-Structured data

In this article, we will discuss the semi-structured data. Data can be defined as the distinct piece of information that is gathered and translated for some purpose. It can be...

5 minutes read.