Related Articles

# Convert a given Binary Tree to Doubly Linked List | Set 3

• Difficulty Level : Medium
• Last Updated : 29 May, 2021

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 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. Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

The following two different solutions have been discussed for this problem.
Convert a given Binary Tree to Doubly Linked List | Set 1
Convert a given Binary Tree to Doubly Linked List | Set 2

In this post, a third solution is discussed which seems to be the simplest of all. The idea is to do in order traversal of the binary tree. While doing inorder traversal, keep track of the previously visited node in a variable, say prev. For every visited node, make it next to the prev and previous of this node as prev.
Thanks to rahul, wishall and all other readers for their useful comments on the above two posts.

The following is the implementation of this solution.

## C++

 `// A C++ program for in-place conversion of Binary Tree to DLL``#include ``using` `namespace` `std;` `/* A binary tree node has data, and left and right pointers */``struct` `node``{``    ``int` `data;``    ``node* left;``    ``node* right;``};` `// 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` `BinaryTree2DoubleLinkedList(node *root, node **head)``{``    ``// Base case``    ``if` `(root == NULL) ``return``;` `    ``// Initialize previously visited node as NULL. This is``    ``// static so that the same value is accessible in all recursive``    ``// calls``    ``static` `node* prev = NULL;` `    ``// Recursively convert left subtree``    ``BinaryTree2DoubleLinkedList(root->left, head);` `    ``// Now convert this node``    ``if` `(prev == NULL)``        ``*head = root;``    ``else``    ``{``        ``root->left = prev;``        ``prev->right = root;``    ``}``    ``prev = root;` `    ``// Finally convert right subtree``    ``BinaryTree2DoubleLinkedList(root->right, head);``}` `/* Helper function that allocates a new node with the``   ``given data and NULL left and right pointers. */``node* newNode(``int` `data)``{``    ``node* new_node = ``new` `node;``    ``new_node->data = data;``    ``new_node->left = new_node->right = NULL;``    ``return` `(new_node);``}` `/* Function to print nodes in a given doubly linked list */``void` `printList(node *node)``{``    ``while` `(node!=NULL)``    ``{``        ``cout << node->data << ``" "``;``        ``node = node->right;``    ``}``}` `/* Driver program to test above functions*/``int` `main()``{``    ``// 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);` `    ``// Convert to DLL``    ``node *head = NULL;``    ``BinaryTree2DoubleLinkedList(root, &head);` `    ``// Print the converted list``    ``printList(head);` `    ``return` `0;``}`

## Java

 `// A Java program for in-place conversion of Binary Tree to DLL`` ` `// A binary tree node has data, left pointers and right pointers``class` `Node``{``    ``int` `data;``    ``Node left, right;`` ` `    ``public` `Node(``int` `data)``    ``{``        ``this``.data = data;``        ``left = right = ``null``;``    ``}``}`` ` `class` `BinaryTree``{``    ``Node root;``     ` `    ``// head --> Pointer to head node of created doubly linked list``    ``Node head;``     ` `    ``// Initialize previously visited node as NULL. This is``    ``// static so that the same value is accessible in all recursive``    ``// calls``    ``static` `Node prev = ``null``;`` ` `    ``// A simple recursive function to convert a given Binary tree``    ``// to Doubly Linked List``    ``// root --> Root of Binary Tree``    ``void` `BinaryTree2DoubleLinkedList(Node root)``    ``{``        ``// Base case``        ``if` `(root == ``null``)``            ``return``;`` ` `        ``// Recursively convert left subtree``        ``BinaryTree2DoubleLinkedList(root.left);`` ` `        ``// Now convert this node``        ``if` `(prev == ``null``)``            ``head = root;``        ``else``        ``{``            ``root.left = prev;``            ``prev.right = root;``        ``}``        ``prev = root;`` ` `        ``// Finally convert right subtree``        ``BinaryTree2DoubleLinkedList(root.right);``    ``}`` ` `    ``/* Function to print nodes in a given doubly linked list */``    ``void` `printList(Node node)``    ``{``        ``while` `(node != ``null``)``        ``{``            ``System.out.print(node.data + ``" "``);``            ``node = node.right;``        ``}``    ``}`` ` `    ``// Driver program to test above functions``    ``public` `static` `void` `main(String[] args)``    ``{``        ``// Let us create the tree as shown in above diagram``        ``BinaryTree tree = ``new` `BinaryTree();``        ``tree.root = ``new` `Node(``10``);``        ``tree.root.left = ``new` `Node(``12``);``        ``tree.root.right = ``new` `Node(``15``);``        ``tree.root.left.left = ``new` `Node(``25``);``        ``tree.root.left.right = ``new` `Node(``30``);``        ``tree.root.right.left = ``new` `Node(``36``);`` ` `        ``// convert to DLL``        ``tree.BinaryTree2DoubleLinkedList(tree.root);``         ` `        ``// Print the converted List``        ``tree.printList(tree.head);`` ` `    ``}``}``// This code has been contributed by Mayank Jaiswal(mayank_24)`

## Python3

 `# Python program for conversion of``# binary tree to doubly linked list.``class` `Node:``    ``def` `__init__(``self``, val):``        ``self``.right ``=` `None``        ``self``.data ``=` `val``        ``self``.left ``=` `None`  `class` `BtoDll:``    ``def` `__init__(``self``):``        ``self``.head ``=` `None``        ``self``.tail ``=` `None` `    ``def` `convert(``self``, root):``      ` `        ``# Base case``        ``if` `root ``is` `None``:``            ``return``          ` `        ``# Recursively convert left subtree``        ``self``.convert(root.left)``        ` `        ``# Now convert this node``        ``node ``=` `root``        ``if` `self``.head ``is` `None``:``            ``self``.head ``=` `node``        ``else``:``            ``self``.tail.right ``=` `node``            ``node.left ``=` `self``.tail``        ``self``.tail ``=` `node``        ` `        ``# Finally convert right subtree``        ``self``.convert(root.right)``        ``return` `self``.head`  `def` `BinaryTree2DoubleLinkedList(root):``    ``'''``    ``A simple recursive function to convert a given Binary tree ``    ``to Doubly Linked List``    ``root --> Root of Binary Tree``    ``'''``    ``converter ``=` `BtoDll()``    ``return` `converter.convert(root)`  `def` `print_dll(head):``    ``'''Function to print nodes in given doubly linked list'''``    ``while` `head ``is` `not` `None``:``        ``print``(head.data, end``=``" "``)``        ``head ``=` `head.right`  `#  Driver program to test above functions``if` `__name__ ``=``=` `"__main__"``:``  ` `    ``# Let us create the tree as``    ``# shown in above diagram``    ``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``)``    ` `    ``# convert to DLL``    ``head ``=` `BinaryTree2DoubleLinkedList(root)``    ` `    ``# Print the converted list``    ``print_dll(head)``    ` `# This code is contributed by codesankalp (SANKALP)`

## C#

 `// A C# program for in-place conversion``// of Binary Tree to DLL``using` `System;` `// A binary tree node has data, left``// pointers and right pointers``public` `class` `Node``{``    ``public` `int` `data;``    ``public` `Node left, right;` `    ``public` `Node(``int` `data)``    ``{``        ``this``.data = data;``        ``left = right = ``null``;``    ``}``}` `class` `GFG``{``public` `Node root;` `// head --> Pointer to head node of``// created doubly linked list``public` `Node head;` `// Initialize previously visited node``// as NULL. This is static so that the``// same value is accessible in all``// recursive calls``public` `static` `Node prev = ``null``;` `// A simple recursive function to``// convert a given Binary tree``// to Doubly Linked List``// root --> Root of Binary Tree``public` `virtual` `void` `BinaryTree2DoubleLinkedList(Node root)``{``    ``// Base case``    ``if` `(root == ``null``)``    ``{``        ``return``;``    ``}` `    ``// Recursively convert left subtree``    ``BinaryTree2DoubleLinkedList(root.left);` `    ``// Now convert this node``    ``if` `(prev == ``null``)``    ``{``        ``head = root;``    ``}``    ``else``    ``{``        ``root.left = prev;``        ``prev.right = root;``    ``}``    ``prev = root;` `    ``// Finally convert right subtree``    ``BinaryTree2DoubleLinkedList(root.right);``}` `/* Function to print nodes in a``   ``given doubly linked list */``public` `virtual` `void` `printList(Node node)``{``    ``while` `(node != ``null``)``    ``{``        ``Console.Write(node.data + ``" "``);``        ``node = node.right;``    ``}``}` `// Driver Code``public` `static` `void` `Main(``string``[] args)``{``    ``// Let us create the tree as``    ``// shown in above diagram``    ``GFG tree = ``new` `GFG();``    ``tree.root = ``new` `Node(10);``    ``tree.root.left = ``new` `Node(12);``    ``tree.root.right = ``new` `Node(15);``    ``tree.root.left.left = ``new` `Node(25);``    ``tree.root.left.right = ``new` `Node(30);``    ``tree.root.right.left = ``new` `Node(36);` `    ``// convert to DLL``    ``tree.BinaryTree2DoubleLinkedList(tree.root);` `    ``// Print the converted List``    ``tree.printList(tree.head);` `}``}` `// This code is contributed by Shrikant13`

## Javascript

 ``

Output:

`25 12 30 10 36 15`

Note that the use of static variables like above is not a recommended practice (we have used static for simplicity). Imagine a situation where the same function is called for two or more trees. The old value of prev would be used in the next call for a different tree. To avoid such problems, we can use a double-pointer or reference to a pointer.
Time Complexity: The above program does a simple inorder traversal, so time complexity is O(n) where n is the number of nodes in given binary tree.