×

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

Bitwise Operators and their Important Tricks

In most of the programs you write today, you deal with data types comprising bytes, such as integer, float, double, etc. Dealing with bytes? It is a quite normal task,...

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

Find the nth node from the end of a Linked List

Find the nth node from the end of a Linked List In this problem, we have given a singly linked list and a number 'n,' and we need to find the...

3 minutes read.

Merge Sort

Merge Sort is one of the most widely used sorting algorithms, and it is based on the Divide and Conquer principle. A problem is subdivided into multiple sub-problems in this method....

8 minutes read.

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

2 minutes read.

Optimal binary search tree using dynamic programming

Implementation // We are creating a presentation where we will present a recursive method of the optimal binary search tree problem.  #include <bits/stdc++.h> using namespace std; //creating a utility function that will help us...

9 minutes read.

Threaded Binary Tree

The linked form of binary trees wastes storage capacity because more than half of the connection variables have a Missing value. A binary tree has several nodes. Hence n+1 link fields...

8 minutes read.

Serialize and Deserialize a Binary Tree

Implementation // Writing a C++ program to check the serialization and deserialization of binary tree.   #include <iosstream> /* A binary tree node contains a key and a pointer to the left and right...

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

Threaded Binary Trees

Introduction Threaded Binary Trees (TBTs) are an enhancement of normal binary trees intended for in-order traversal only. This means that this data structure is developed with the objective of making the...

12 minutes read.

Insertion Sort vs Bubble Sort

In this article, we will see the major differences between Insertion Sort and Bubble Sort. Before that, let’s have a quick overview of what these sorting algorithms are and what’s...

4 minutes read.

Given a Binary Tree Return All Root-to-Leaf Paths

Implementation #include <bits/stdc++.h> using namespace std; // A binary tree node generally consists of data, a pointer to the left and right child, and a pointer to the right child.  class __nod { public: int record; __nod* Lft; __nod*...

9 minutes read.

Recursion - Factorial and Fibonacci

In this article, we will learn how to find the factorial of a number and the Fibonacci series up to n using the recursion method. What is recursion? Defining anything in terms...

7 minutes read.

Union and Intersection of two Linked Lists

Union and Intersection of two Linked Lists This article explains how we can do the union and intersection of two linked lists. In this problem, we have given two linked lists...

3 minutes read.

Stack vs Array

Difference between Array and Stack In this article, we are going to discuss the major differences between the stack and array data structures: Array – In the data structure, the array is...

3 minutes read.

About Data Structures

What exactly are data structures? A data structure is a type of storage that is used to organise and store data. It is a method of organising data on a computer...

5 minutes read.

Primitive Data Structure in C

The data structure is a logical or mathematical model for organizing and structuring the main memory or elements. We can classify the data structures in two ways one is primitive, and...

10 minutes read.

Length of longest palindrome in a linked list using O(1) extra space

Length of longest palindrome in a linked list using O(1) extra space In this problem, we need to find the length of the longest palindrome list that is present in given...

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.

Merge two sorted linked lists

Merge two sorted linked lists In this article, we are going to learn how to merge two linked lists. Here we have given two linked lists that are sorted in increasing...

7 minutes read.