Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Tree
  • Practice Tree
  • MCQs on Tree
  • Tutorial on Tree
  • Types of Trees
  • Basic operations
  • Tree Traversal
  • Binary Tree
  • Complete Binary Tree
  • Ternary Tree
  • Binary Search Tree
  • Red-Black Tree
  • AVL Tree
  • Full Binary Tree
  • B-Tree
  • Advantages & Disadvantages
Open In App
Next Article:
Convert Binary Tree to Doubly Linked List by fixing left and right pointers
Next article icon

Convert given Binary Tree to Doubly Linked List in Linear time

Last Updated : 23 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Given a Binary Tree (BT), the task is to convert it to a Doubly Linked List (DLL) in place. The left and right pointers in nodes will be used as previous and next pointers respectively in converted DLL. The order of nodes in DLL must be the same as the order of the given Binary Tree. The first node of Inorder traversal (leftmost node in BT) must be the head node of the DLL.

Examples:

Input:

Convert-Binary-Tree-to-Doubly-Linked-List-using-inorder-traversal-ex-1

Output:

Convert-Binary-Tree-to-Doubly-Linked-List-using-inorder-traversal-1


Explanation: The above binary tree is converted into doubly linked list where left pointer of the binary tree node act as the previous node and right pointer of the binary tree node act as the next node.


Input:

Convert-Binary-Tree-to-Doubly-Linked-List-using-inorder-traversal-ex-2

Output:

Convert-Binary-Tree-to-Doubly-Linked-List-using-inorder-traversal-2


Explanation: The above binary tree is converted into doubly linked list where left pointer of the binary tree node act as the previous node and right pointer of the binary tree node act as the next node.

Approach:

In the following implementation, we traverse the tree in inorder fashion. We add nodes at the beginning of current linked list and update head of the list using pointer to head pointer. Since we insert at the beginning, we need to process leaves in reverse order. For reverse order, we first traverse the right subtree before the left subtree. i.e. do a reverse inorder traversal. 

C++
// C++ program to convert a given Binary  // Tree to Doubly Linked List  #include <bits/stdc++.h> using namespace std;  class Node {      	public:     int data;     Node *left, *right;   	Node(int x) {      	data = x;       	left = right = nullptr;     } };  // A simple recursive function to convert a given // Binary tree to Doubly Linked List // root    --> Root of Binary Tree // head --> Pointer to head node of created doubly linked list void BToDLL(Node* root, Node*& head) {        // Base cases     if (root == nullptr)         return;      // Recursively convert right subtree     BToDLL(root->right, head);      // insert root into DLL     root->right = head;      // Change left pointer of previous head     if (head != nullptr)         head->left = root;      // Change head of Doubly linked list     head = root;      // Recursively convert left subtree     BToDLL(root->left, head); }   Node* bToDLL(Node* root) {   	 	Node* head = nullptr;     BToDLL(root, head);     return head; }  void printList(Node* head) {        while (head) {         cout<< head->data << " ";         head = head->right;     } }   int main() {         // Constructing below tree       //         5       //        / \       //      3     6       //     / \     \       //     1  4     8       //    / \      / \       //    0 2      7  9     Node* root = new Node(5);     root->left = new Node(3);     root->right = new Node(6);     root->left->left = new Node(1);     root->left->right = new Node(4);     root->right->right = new Node(8);     root->left->left->left = new Node(0);     root->left->left->right = new Node(2);     root->right->right->left = new Node(7);     root->right->right->right = new Node(9);      	Node*head = bToDLL(root);   	printList(head);      return 0; } 
Java
// Java program to convert a given Binary  // Tree to Doubly Linked List  class Node {     int data;     Node left, right;      Node(int x) {         data = x;         left = right = null;     } }  class GfG {      // A simple recursive function to convert a given     // Binary tree to Doubly Linked List     // root    --> Root of Binary Tree     // head --> Pointer to head node of created doubly linked list     static void BToDLL(Node root, Node[] head) {                // Base cases         if (root == null) {             return;         }          // Recursively convert right subtree         BToDLL(root.right, head);          // insert root into DLL         root.right = head[0];          // Change left pointer of previous head         if (head[0] != null) {             head[0].left = root;         }          // Change head of Doubly linked list         head[0] = root;          // Recursively convert left subtree         BToDLL(root.left, head);     }      static Node bToDLL(Node root) {         Node[] head = new Node[1];         BToDLL(root, head);         return head[0];     }      // Function to print the doubly linked list     static void printList(Node head) {         while (head != null) {             System.out.print(head.data + " ");             head = head.right;         }         System.out.println();     }      public static void main(String[] args) {                // Constructing the binary tree:         //         5          //        / \          //      3     6          //     / \     \          //     1  4     8          //    / \      / \          //    0 2      7  9          Node root = new Node(5);         root.left = new Node(3);         root.right = new Node(6);         root.left.left = new Node(1);         root.left.right = new Node(4);         root.right.right = new Node(8);         root.left.left.left = new Node(0);         root.left.left.right = new Node(2);         root.right.right.left = new Node(7);         root.right.right.right = new Node(9);          Node head = bToDLL(root);         printList(head);     } } 
Python
# Python program to convert a given Binary  # Tree to Doubly Linked List  class Node:     def __init__(self, x):         self.data = x         self.left = None         self.right = None   def BToDLL(root, head):        # Base case     if root is None:         return      # Recursively convert the right subtree     BToDLL(root.right, head)      # Insert the root into DLL     root.right = head[0]      # Change the left pointer of the previous head     if head[0] is not None:         head[0].left = root      # Change the head of Doubly Linked List     head[0] = root      # Recursively convert the left subtree     BToDLL(root.left, head)   def bToDLL(root):     head = [None]     BToDLL(root, head)     return head[0]   def printList(head):     while head:         print(head.data, end=" ")         head = head.right     print()   if __name__ == "__main__":        # Constructing the below tree     #         5      #        / \      #      3     6      #     / \     \      #     1  4     8      #    / \      / \      #    0 2      7  9      root = Node(5)     root.left = Node(3)     root.right = Node(6)     root.left.left = Node(1)     root.left.right = Node(4)     root.right.right = Node(8)     root.left.left.left = Node(0)     root.left.left.right = Node(2)     root.right.right.left = Node(7)     root.right.right.right = Node(9)      head = bToDLL(root)     printList(head) 
C#
// C# program to convert a given Binary // Tree to Doubly Linked List using System;  class Node {     public int data;     public Node left, right;      public Node(int x) {         data = x;         left = right = null;     } }  class GfG {      // Helper method to convert the binary tree to DLL     static void BToDLL(Node root, ref Node head) {          // Base case: if root is null, return         if (root == null)             return;          // Recursively convert the right subtree         BToDLL(root.right, ref head);          // Insert the root node into DLL         root.right = head;          // If head is not null, change the left         // pointer of the previous head         if (head != null)             head.left = root;          // Move head to the current root         head = root;          // Recursively convert the left subtree         BToDLL(root.left, ref head);     }      // Wrapper function to initiate the conversion     static Node bToDLL(Node root) {          Node head = null;         BToDLL(root, ref head);         return head;     }      // Function to print the DLL     static void PrintList(Node head) {          Node current = head;         while (current != null) {             Console.Write(current.data + " ");             current = current.right;         }     }      static void Main() {                // Constructing the below tree:         //         5         //        / \          //      3     6         //     / \     \          //     1  4     8         //    / \      / \          //    0 2      7  9          Node root = new Node(5);         root.left = new Node(3);         root.right = new Node(6);         root.left.left = new Node(1);         root.left.right = new Node(4);         root.right.right = new Node(8);         root.left.left.left = new Node(0);         root.left.left.right = new Node(2);         root.right.right.left = new Node(7);         root.right.right.right = new Node(9);         Node head = bToDLL(root);          PrintList(head);     } } 
JavaScript
// JavaScript program to convert a given Binary // Tree to Doubly Linked List class Node {     constructor(x) {         this.data = x;         this.left = null;         this.right = null;     } }  // Helper function to convert binary tree to DLL function BToDLL(root, head) {      // Base case: if root is null, return     if (root === null)         return;      // Recursively convert the right subtree     BToDLL(root.right, head);      // Insert the root node into DLL     root.right = head[0];      // If head is not null, change the left pointer of     // the previous head     if (head[0] !== null) {         head[0].left = root;     }      // Move head to the current root     head[0] = root;      // Recursively convert the left subtree     BToDLL(root.left, head); }  // Wrapper function to initiate the conversion function bToDLL(root) {     let head = [ null ];     BToDLL(root, head);     return head[0]; }  // Function to print the DLL function printList(head) {      let current = head;     while (current !== null) {         console.log(current.data + " ");         current = current.right;     }     console.log(); }  // Constructing the below tree: //         5 //        / \   //      3     6 //     / \     \   //     1  4     8 //    / \      / \   //    0 2      7  9  let root = new Node(5); root.left = new Node(3); root.right = new Node(6); root.left.left = new Node(1); root.left.right = new Node(4); root.right.right = new Node(8); root.left.left.left = new Node(0); root.left.left.right = new Node(2); root.right.right.left = new Node(7); root.right.right.right = new Node(9);  let head = bToDLL(root); printList(head); 

Output
0 1 2 3 4 5 6 7 8 9 

Time Complexity: O(n), as the solution does a single traversal of given Binary Tree.
Auxiliary Space: O(n)

Related articles:

  • Convert Binary Tree to Doubly Linked List using inorder traversal
  • Convert Binary Tree to Doubly Linked List by fixing left and right pointers
  • Convert Binary Tree to Doubly Linked List by keeping track of visited node


Next Article
Convert Binary Tree to Doubly Linked List by fixing left and right pointers

A

Aditya Goel
Improve
Article Tags :
  • DSA
  • Linked List
  • Tree
  • Amazon
  • doubly linked list
  • Goldman Sachs
  • Microsoft
Practice Tags :
  • Amazon
  • Goldman Sachs
  • Microsoft
  • Linked List
  • Tree

Similar Reads

  • Convert a Binary Tree into Doubly Linked List in spiral fashion
    Given a binary tree, convert it into a doubly linked list (DLL) where the nodes are arranged in a spiral order. The left pointer of the binary tree node should act as the previous node in the DLL, and the right pointer should act as the next node in the DLL. The solution should not allocate extra me
    10 min read
  • Convert Binary Tree to Doubly Linked List using inorder traversal
    Given a Binary Tree (BT), the task is to convert it to a Doubly Linked List (DLL) in place. The left and right pointers in nodes will be used as previous and next pointers respectively in converted DLL. The order of nodes in DLL must be the same as the order of the given Binary Tree. The first node
    15+ min read
  • Convert Binary Tree to Doubly Linked List by fixing left and right pointers
    Given a Binary Tree, the task is to convert it to a Doubly Linked List (DLL) in place. The left and right pointers in nodes will be used as previous and next pointers respectively in converted DLL. The order of nodes in DLL must be the same as the order of the given Binary Tree. The first node of In
    10 min read
  • Insert a Node before a given node in Doubly Linked List
    Given a Doubly Linked List, the task is to insert a new node before a given node in the linked list. Examples: Input: Linked List = 1 <-> 3 <-> 4, newData = 2, key = 3Output: Linked List = 1 <-> 2 <-> 3 <-> 4Explanation: New node with data 2 is inserted before the node
    12 min read
  • Insert a Node after a given node in Doubly Linked List
    Given a Doubly Linked List, the task is to insert a new node after a given node in the linked list. Examples: Input: Linked List = 1 <-> 2 <-> 4, newData = 3, key = 2Output: Linked List = 1 <-> 2 <-> 3 <-> 4Explanation: New node 3 is inserted after key, that is node 2.
    11 min read
  • Extract Leaves of a Binary Tree in a Doubly Linked List
    Given a Binary Tree, extract all leaves of it in a Doubly Linked List (DLL). Note that the DLL need to be created in-place. Assume that the node structure of DLL and Binary Tree is same, only the meaning of left and right pointers are different. In DLL, left means previous pointer, and right means n
    11 min read
  • Convert Binary Tree to Doubly Linked List by keeping track of visited node
    Given a Binary Tree, The task is to convert it to a Doubly Linked List keeping the same order.  The left and right pointers in nodes are to be used as previous and next pointers respectively in converted DLL. The order of nodes in DLL must be the same as in Inorder for the given Binary Tree. The fir
    15+ min read
  • 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
    15 min read
  • Convert Binary Tree to Doubly Linked List using Morris Traversal
    Given a Binary Tree (BT), convert it to a Doubly Linked List (DLL). The left and right pointers in nodes are to be used as previous and next pointers respectively in converted DLL. The order of nodes in DLL must be the same as in Inorder for the given Binary Tree. The first node of Inorder traversal
    12 min read
  • Convert a Binary Tree to a Circular Doubly Link List
    Given a Binary Tree, convert it to a Circular Doubly Linked List (In-Place). The left and right pointers in nodes are to be used as previous and next pointers respectively in the converted Circular Linked List.The order of nodes in the List must be the same as in Inorder for the given Binary Tree.Th
    15+ min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences