Open In App

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

Last Updated : 10 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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 (leftmost node in BT) must be the head node of the DLL.  

TreeToList

A solution to this problem has been discussed in this post
In this post, another simple and efficient solution is discussed. The solution discussed here has two simple steps.

  1. Fix Left Pointers: In this step, we change left pointers to point to previous nodes in DLL. The idea is simple, we do in order traversal of the tree. In order to traversal, we keep track of the previously visited node and change the left pointer to the previous node. See fixPrevPtr() implementation below. 
  2. Fix Right Pointers: The above is intuitive and simple. How to change the right pointers to point to the next node in DLL? The idea is to use left pointers fixed in step 1. We start from the rightmost node in Binary Tree (BT). The rightmost node is the last node in DLL. Since left pointers are changed to point to the previous node in DLL, we can linearly traverse the complete DLL using these pointers. The traversal would be from last to the first node. While traversing the DLL, we keep track of the previously visited node and change the right pointer to the previous node. See fixNextPtr() implementation below.  

Implementation:

C++




// A simple inorder traversal based
// program to convert a Binary Tree to DLL
#include <bits/stdc++.h>
using namespace std;
 
// A tree node
class node
{
    public:
    int data;
    node *left, *right;
};
 
// A utility function to create
// a new tree node
node *newNode(int data)
{
    node *Node = new node();
    Node->data = data;
    Node->left = Node->right = NULL;
    return(Node);
}
 
// Standard Inorder traversal of tree
void inorder(node *root)
{
    if (root != NULL)
    {
        inorder(root->left);
        cout << "\t" << root->data;
        inorder(root->right);
    }
}
 
// Changes left pointers to work as
// previous pointers in converted DLL
// The function simply does inorder
// traversal of Binary Tree and updates
// left pointer using previously visited node
void fixPrevPtr(node *root)
{
    static node *pre = NULL;
 
    if (root != NULL)
    {
        fixPrevPtr(root->left);
        root->left = pre;
        pre = root;
        fixPrevPtr(root->right);
    }
}
 
// Changes right pointers to work
// as next pointers in converted DLL
node *fixNextPtr(node *root)
{
    node *prev = NULL;
 
    // Find the right most node
    // in BT or last node in DLL
    while (root && root->right != NULL)
        root = root->right;
 
    // Start from the rightmost node,
    // traverse back using left pointers.
    // While traversing, change right pointer of nodes.
    while (root && root->left != NULL)
    {
        prev = root;
        root = root->left;
        root->right = prev;
    }
 
    // The leftmost node is head
    // of linked list, return it
    return (root);
}
 
// The main function that converts
// BST to DLL and returns head of DLL
node *BTToDLL(node *root)
{
    // Set the previous pointer
    fixPrevPtr(root);
 
    // Set the next pointer and return head of DLL
    return fixNextPtr(root);
}
 
// Traverses the DLL from left to right
void printList(node *root)
{
    while (root != NULL)
    {
        cout<<"\t"<<root->data;
        root = root->right;
    }
}
 
// Driver code
int main(void)
{
    // Let us create the tree
    // shown in above diagram
    node *root = newNode(10);
    root->left = newNode(12);
    root->right = newNode(15);
    root->left->left = newNode(25);
    root->left->right = newNode(30);
    root->right->left = newNode(36);
 
    cout<<"\n\t\tInorder Tree Traversal\n\n";
    inorder(root);
 
    node *head = BTToDLL(root);
 
    cout << "\n\n\t\tDLL Traversal\n\n";
    printList(head);
    return 0;
}
 
// This code is contributed by rathbhupendra


C




// A simple inorder traversal based program to convert a Binary Tree to DLL
#include<stdio.h>
#include<stdlib.h>
 
// A tree node
struct node
{
    int data;
    struct node *left, *right;
};
 
// A utility function to create a new tree node
struct node *newNode(int data)
{
    struct node *node = (struct node *)malloc(sizeof(struct node));
    node->data = data;
    node->left = node->right = NULL;
    return(node);
}
 
// Standard Inorder traversal of tree
void inorder(struct node *root)
{
    if (root != NULL)
    {
        inorder(root->left);
        printf("\t%d",root->data);
        inorder(root->right);
    }
}
 
// Changes left pointers to work as previous pointers in converted DLL
// The function simply does inorder traversal of Binary Tree and updates
// left pointer using previously visited node
void fixPrevPtr(struct node *root)
{
    static struct node *pre = NULL;
 
    if (root != NULL)
    {
        fixPrevPtr(root->left);
        root->left = pre;
        pre = root;
        fixPrevPtr(root->right);
    }
}
 
// Changes right pointers to work as next pointers in converted DLL
struct node *fixNextPtr(struct node *root)
{
    struct node *prev = NULL;
 
    // Find the right most node in BT or last node in DLL
    while (root && root->right != NULL)
        root = root->right;
 
    // Start from the rightmost node, traverse back using left pointers.
    // While traversing, change right pointer of nodes.
    while (root && root->left != NULL)
    {
        prev = root;
        root = root->left;
        root->right = prev;
    }
 
    // The leftmost node is head of linked list, return it
    return (root);
}
 
// The main function that converts BST to DLL and returns head of DLL
struct node *BTToDLL(struct node *root)
{
    // Set the previous pointer
    fixPrevPtr(root);
 
    // Set the next pointer and return head of DLL
    return fixNextPtr(root);
}
 
// Traverses the DLL from left to right
void printList(struct node *root)
{
    while (root != NULL)
    {
        printf("\t%d", root->data);
        root = root->right;
    }
}
 
// Driver program to test above functions
int main(void)
{
    // Let us create the tree shown in above diagram
    struct node *root = newNode(10);
    root->left        = newNode(12);
    root->right       = newNode(15);
    root->left->left  = newNode(25);
    root->left->right = newNode(30);
    root->right->left = newNode(36);
 
    printf("\n\t\tInorder Tree Traversal\n\n");
    inorder(root);
 
    struct node *head = BTToDLL(root);
 
    printf("\n\n\t\tDLL Traversal\n\n");
    printList(head);
    return 0;
}


Java




// Java program to convert BTT to DLL using
// simple inorder traversal
 
public class BinaryTreeToDLL
{
    static class node
    {
        int data;
        node left, right;
 
        public node(int data)
        {
            this.data = data;
        }
    }
 
    static node prev;
 
    // Changes left pointers to work as previous
    // pointers in converted DLL The function
    // simply does inorder traversal of Binary
    // Tree and updates left pointer using
    // previously visited node
    static void fixPrevptr(node root)
    {
        if (root == null)
            return;
 
        fixPrevptr(root.left);
        root.left = prev;
        prev = root;
        fixPrevptr(root.right);
 
    }
 
    // Changes right pointers to work
    // as next pointers in converted DLL
    static node fixNextptr(node root)
    {       
        // Find the right most node in
        // BT or last node in DLL
        while (root.right != null)
            root = root.right;
 
        // Start from the rightmost node, traverse
        // back using left pointers. While traversing,
        // change right pointer of nodes
        while (root != null && root.left != null)
        {
            node left = root.left;
            left.right = root;
            root = root.left;
        }
 
        // The leftmost node is head of linked list, return it
        return root;
    }
 
    static node BTTtoDLL(node root)
    {
        prev = null;
 
        // Set the previous pointer
        fixPrevptr(root);
 
        // Set the next pointer and return head of DLL
        return fixNextptr(root);
    }
 
    // Traverses the DLL from left to right
    static void printlist(node root)
    {
        while (root != null)
        {
            System.out.print(root.data + " ");
            root = root.right;
        }
    }
 
    // Standard Inorder traversal of tree
    static void inorder(node root)
    {
        if (root == null)
            return;
        inorder(root.left);
        System.out.print(root.data + " ");
        inorder(root.right);
    }
 
    public static void main(String[] args)
    {
        // Let us create the tree shown in above diagram
        node root = new node(10);
        root.left = new node(12);
        root.right = new node(15);
        root.left.left = new node(25);
        root.left.right = new node(30);
        root.right.left = new node(36);
 
        System.out.println("Inorder Tree Traversal");
        inorder(root);
 
        node head = BTTtoDLL(root);
 
        System.out.println("\nDLL Traversal");
        printlist(head);
    }
}
 
// This code is contributed by Rishabh Mahrsee


Python3




# A simple inorder traversal based program to convert a
# Binary Tree to DLL
 
# A Binary Tree node
class Node:
     
    # Constructor to create a new tree node
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
 
# Standard Inorder traversal of tree
def inorder(root):
     
    if root is not None:
        inorder(root.left)
        print ("\t%d" %(root.data),end=" ")
        inorder(root.right)
 
# Changes left pointers to work as previous pointers
# in converted DLL
# The function simply does inorder traversal of
# Binary Tree and updates
# left pointer using previously visited node
def fixPrevPtr(root):
    if root is not None:
        fixPrevPtr(root.left)
        root.left = fixPrevPtr.pre
        fixPrevPtr.pre = root
        fixPrevPtr(root.right)
 
# Changes right pointers to work as next pointers in
# converted DLL
def fixNextPtr(root):
 
    prev = None
    # Find the right most node in BT or last node in DLL
    while(root and root.right != None):
        root = root.right
 
    # Start from the rightmost node, traverse back using
    # left pointers
    # While traversing, change right pointer of nodes
    while(root and root.left != None):
        prev = root
        root = root.left
        root.right = prev
 
    # The leftmost node is head of linked list, return it
    return root
 
# The main function that converts BST to DLL and returns
# head of DLL
def BTToDLL(root):
     
    # Set the previous pointer
    fixPrevPtr(root)
 
    # Set the next pointer and return head of DLL
    return fixNextPtr(root)
 
# Traverses the DLL from left to right
def printList(root):
    while(root != None):
        print ("\t%d" %(root.data),end=" ")
        root = root.right
 
# Driver program to test above function
root = Node(10)
root.left = Node(12)
root.right = Node(15)
root.left.left = Node(25)
root.left.right = Node(30)
root.right.left = Node(36)
 
print ("Inorder Tree Traversal")
inorder(root)
 
# Static variable pre for function fixPrevPtr
fixPrevPtr.pre = None
head = BTToDLL(root)
 
print ("\nDLL Traversal")
printList(head)
     
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)


C#




// C# program to convert BTT to DLL using
// simple inorder traversal
using System;
 
class GFG
{
public class node
{
    public int data;
    public node left, right;
 
    public node(int data)
    {
        this.data = data;
    }
}
 
public static node prev;
 
// Changes left pointers to work as previous
// pointers in converted DLL The function
// simply does inorder traversal of Binary
// Tree and updates left pointer using
// previously visited node
public static void fixPrevptr(node root)
{
    if (root == null)
    {
        return;
    }
 
    fixPrevptr(root.left);
    root.left = prev;
    prev = root;
    fixPrevptr(root.right);
 
}
 
// Changes right pointers to work
// as next pointers in converted DLL
public static node fixNextptr(node root)
{
    // Find the right most node in
    // BT or last node in DLL
    while (root.right != null)
    {
        root = root.right;
    }
 
    // Start from the rightmost node, traverse
    // back using left pointers. While traversing,
    // change right pointer of nodes
    while (root != null && root.left != null)
    {
        node left = root.left;
        left.right = root;
        root = root.left;
    }
 
    // The leftmost node is head of
    // linked list, return it
    return root;
}
 
public static node BTTtoDLL(node root)
{
    prev = null;
 
    // Set the previous pointer
    fixPrevptr(root);
 
    // Set the next pointer and
    // return head of DLL
    return fixNextptr(root);
}
 
// Traverses the DLL from left to right
public static void printlist(node root)
{
    while (root != null)
    {
        Console.Write(root.data + " ");
        root = root.right;
    }
}
 
// Standard Inorder traversal of tree
public static void inorder(node root)
{
    if (root == null)
    {
        return;
    }
    inorder(root.left);
    Console.Write(root.data + " ");
    inorder(root.right);
}
 
public static void Main()
{
    // Let us create the tree
    // shown in above diagram
    node root = new node(10);
    root.left = new node(12);
    root.right = new node(15);
    root.left.left = new node(25);
    root.left.right = new node(30);
    root.right.left = new node(36);
 
    Console.WriteLine("Inorder Tree Traversal");
    inorder(root);
 
    node head = BTTtoDLL(root);
 
    Console.WriteLine("\nDLL Traversal");
    printlist(head);
}
}
 
// This code is contributed by Shrikant13


Javascript




<script>
    // javascript program to convert BTT to DLL using
    // simple inorder traversal
 
    class node {
        constructor(val) {
            this.data = val;
            this.left = null;
            this.right = null;
        }
    }
    var prev;
 
    // Changes left pointers to work as previous
    // pointers in converted DLL The function
    // simply does inorder traversal of Binary
    // Tree and updates left pointer using
    // previously visited node
    function fixPrevptr( root) {
        if (root == null)
            return;
 
        fixPrevptr(root.left);
        root.left = prev;
        prev = root;
        fixPrevptr(root.right);
 
    }
 
    // Changes right pointers to work
    // as next pointers in converted DLL
    function fixNextptr( root) {
        // Find the right most node in
        // BT or last node in DLL
        while (root.right != null)
            root = root.right;
 
        // Start from the rightmost node, traverse
        // back using left pointers. While traversing,
        // change right pointer of nodes
        while (root != null && root.left != null) {
            var left = root.left;
            left.right = root;
            root = root.left;
        }
 
        // The leftmost node is head of linked list, return it
        return root;
    }   
 
    function BTTtoDLL( root) {
        prev = null;
 
        // Set the previous pointer
        fixPrevptr(root);
 
        // Set the next pointer and return head of DLL
        return fixNextptr(root);
    }
 
    // Traverses the DLL from left to right
    function printlist( root) {
        while (root != null) {
            document.write(root.data + "   ");
            root = root.right;
        }
    }
 
    // Standard Inorder traversal of tree
    function inorder( root) {
        if (root == null)
            return;
        inorder(root.left);
        document.write(root.data + "   ");
        inorder(root.right);
    }
 
     
    // Let us create the tree shown in above diagram
    var root = new node(10);
    root.left = new node(12);
    root.right = new node(15);
    root.left.left = new node(25);
    root.left.right = new node(30);
    root.right.left = new node(36);
 
    document.write("<br/>Inorder Tree Traversal<br/>");
    inorder(root);
 
    var head = BTTtoDLL(root);
 
    document.write("<br/>DLL Traversal<br/>");
    printlist(head);
 
// This code contributed by umadevi9616
</script>


Output

        Inorder Tree Traversal

    25    12    30    10    36    15

        DLL Traversal

    25    12    30    10    36    15

Time Complexity: O(n) where n is the number of nodes in a given Binary Tree. The solution simply does two traversals of all Binary Tree nodes.

Auxiliary Space: O(n)

The extra space is used due to recursion call stack of fixPrevPtr function. The worst case happens when the tree is skewed.
 



Similar Reads

Convert left-right representation of a binary tree to down-right
Left-Right representation of a binary tree is standard representation where every node has a pointer to left child and another pointer to right child.Down-Right representation is an alternate representation where every node has a pointer to left (or first) child and another pointer to next sibling. So siblings at every level are connected from left
10 min read
Sorted insert in a doubly linked list with head and tail pointers
A Doubly linked list is a linked list that consists of a set of sequentially linked records called nodes. Each node contains two fields that are references to the previous and to the next node in the sequence of nodes. The task is to create a doubly linked list by inserting nodes such that list remains in ascending order on printing from left to ri
10 min read
Convert Binary Tree to Circular Doubly Linked List using Linear extra space
Given a Binary Tree, convert it to a Circular Doubly Linked List. 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 the order of the given Binary Tree.The first node of Inorder traversal must be the head node of
12 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 must be the head node of the DLL. Examples: Input
12 min read
Convert given Binary Tree to Doubly Linked List in Linear time
Given a Binary Tree (BT), convert it to a Doubly Linked List(DLL) In-Place. 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 same as Inorder of the given Binary Tree. The first node of Inorder traversal (left most node in BT) must be head node of the D
8 min read
Convert a Binary Tree into Doubly Linked List in spiral fashion
Given a Binary Tree, convert it into a Doubly Linked List where the nodes are represented Spirally. The left pointer of the binary tree node should act as a previous node for created DLL and the right pointer should act as the next node. The solution should not allocate extra memory for DLL nodes. It should use binary tree nodes for creating DLL i.
14 min read
Convert Binary Tree to Doubly Linked List using inorder 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 (leftmost node in BT) must be the head node of the
21 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 first node of Inorder traversal (leftmost node in BT)
22 min read
Print a matrix in alternate manner (left to right then right to left)
Given a 2D array, the task is to print the 2D in alternate manner (First row from left to right, then from right to left, and so on). Examples: Input : arr[][2] = {{1, 2} {2, 3}}; Output : 1 2 3 2 Input :arr[][3] = { { 7 , 2 , 3 }, { 2 , 3 , 4 }, { 5 , 6 , 1 }}; Output : 7 2 3 4 3 2 5 6 1 The solution of this problem is that run two loops and print
5 min read
Modify a binary tree to get preorder traversal using right pointers only
Given a binary tree. Modify it in such a way that after modification you can have a preorder traversal of it using only the right pointers. During modification, you can use right as well as left pointers. Examples: Input : 10 / \ 8 2 / \ 3 5 Output : 10 \ 8 \ 3 \ 5 \ 2 Explanation : The preorder traversal of given binary tree is 10 8 3 5 2. Method
15 min read