Open In App

Convert given Binary Tree to Doubly Linked List in Linear time

Last Updated : 23 Nov, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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:



Next Article

Similar Reads

three90RightbarBannerImg
  翻译: