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) must be the head node of the DLL.
The following two different solutions have been discussed for this problem.
Convert a given Binary Tree to a Doubly Linked List | Set 1
Convert a given Binary Tree to a Doubly Linked List | Set 2
Approach: Below is the idea to solve the problem:
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 set previous of this node as prev.
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
struct node {
int data;
node* left;
node* right;
};
void BinaryTree2DoubleLinkedList(node* root, node** head)
{
if (root == NULL)
return ;
static node* prev = NULL;
BinaryTree2DoubleLinkedList(root->left, head);
if (prev == NULL)
*head = root;
else {
root->left = prev;
prev->right = root;
}
prev = root;
BinaryTree2DoubleLinkedList(root->right, head);
}
node* newNode( int data)
{
node* new_node = new node;
new_node->data = data;
new_node->left = new_node->right = NULL;
return (new_node);
}
void printList(node* node)
{
while (node != NULL) {
cout << node->data << " " ;
node = node->right;
}
}
int main()
{
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);
node* head = NULL;
BinaryTree2DoubleLinkedList(root, &head);
printList(head);
return 0;
}
|
C
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node* left;
struct node* right;
} node;
void BinaryTree2DoubleLinkedList(node* root, node** head)
{
if (root == NULL)
return ;
static node* prev = NULL;
BinaryTree2DoubleLinkedList(root->left, head);
if (prev == NULL)
*head = root;
else {
root->left = prev;
prev->right = root;
}
prev = root;
BinaryTree2DoubleLinkedList(root->right, head);
}
node* newNode( int data)
{
node* new_node = (node*) malloc ( sizeof (node));
new_node->data = data;
new_node->left = new_node->right = NULL;
return (new_node);
}
void printList(node* node)
{
while (node != NULL) {
printf ( "%d " , node->data);
node = node->right;
}
}
int main()
{
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);
node* head = NULL;
BinaryTree2DoubleLinkedList(root, &head);
printList(head);
return 0;
}
|
Java
class Node
{
int data;
Node left, right;
public Node( int data)
{
this .data = data;
left = right = null ;
}
}
class BinaryTree
{
Node root;
Node head;
static Node prev = null ;
void BinaryTree2DoubleLinkedList(Node root)
{
if (root == null )
return ;
BinaryTree2DoubleLinkedList(root.left);
if (prev == null )
head = root;
else
{
root.left = prev;
prev.right = root;
}
prev = root;
BinaryTree2DoubleLinkedList(root.right);
}
void printList(Node node)
{
while (node != null )
{
System.out.print(node.data + " " );
node = node.right;
}
}
public static void main(String[] args)
{
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 );
tree.BinaryTree2DoubleLinkedList(tree.root);
tree.printList(tree.head);
}
}
|
Python3
class Node:
def __init__( self , val):
self .right = None
self .data = val
self .left = None
prev = None
def BinaryTree2DoubleLinkedList(root):
if root is None :
return root
head = BinaryTree2DoubleLinkedList(root.left);
global prev
if prev is None :
head = root
else :
root.left = prev
prev.right = root
prev = root;
BinaryTree2DoubleLinkedList(root.right);
return head
def print_dll(head):
while head is not None :
print (head.data, end = " " )
head = head.right
if __name__ = = '__main__' :
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 )
head = BinaryTree2DoubleLinkedList(root)
print_dll(head)
|
C#
using System;
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;
public Node head;
public static Node prev = null ;
public virtual void BinaryTree2DoubleLinkedList(Node root)
{
if (root == null )
{
return ;
}
BinaryTree2DoubleLinkedList(root.left);
if (prev == null )
{
head = root;
}
else
{
root.left = prev;
prev.right = root;
}
prev = root;
BinaryTree2DoubleLinkedList(root.right);
}
public virtual void printList(Node node)
{
while (node != null )
{
Console.Write(node.data + " " );
node = node.right;
}
}
public static void Main( string [] args)
{
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);
tree.BinaryTree2DoubleLinkedList(tree.root);
tree.printList(tree.head);
}
}
|
Javascript
<script>
class Node {
constructor(val) {
this .data = val;
this .left = null ;
this .right = null ;
}
}
var root;
var head;
var prev = null ;
function BinaryTree2DoubleLinkedList(root)
{
if (root == null )
return ;
BinaryTree2DoubleLinkedList(root.left);
if (prev == null )
head = root;
else
{
root.left = prev;
prev.right = root;
}
prev = root;
BinaryTree2DoubleLinkedList(root.right);
}
function printList(node)
{
while (node != null )
{
document.write(node.data + " " );
node = node.right;
}
}
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);
BinaryTree2DoubleLinkedList(root);
printList(head);
</script>
|
Note: The use of static variables like above is not a recommended practice, here static is used for simplicity. Imagine if 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 a reference to a pointer.
Time Complexity: O(N), The above program does a simple inorder traversal, so time complexity is O(N) where N is the number of nodes in a given Binary tree.
Auxiliary Space: O(N), For recursion call stack.
Convert a given Binary Tree to Doubly Linked List iteratively using Stack data structure:
Do iterative inorder traversal and maintain a prev pointer to point the last visited node then point current node’s perv to prev and prev’s next to current node.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
struct node {
int data;
node* left;
node* right;
};
node * bToDLL(node *root)
{
stack<pair<node*, int >> s;
s.push({root, 0});
vector< int > res;
bool flag = true ;
node* head = NULL;
node* prev = NULL;
while (!s.empty()) {
auto x = s.top();
node* t = x.first;
int state = x.second;
s.pop();
if (state == 3 or t == NULL) continue ;
s.push({t, state+1});
if (state == 0) s.push({t->left, 0});
else if (state == 1) {
if (prev) prev->right = t;
t->left = prev;
prev = t;
if (flag) {
head = t;
flag = false ;
}
}
else if (state == 2) s.push({t->right, 0});
}
return head;
}
node* newNode( int data)
{
node* new_node = new node;
new_node->data = data;
new_node->left = new_node->right = NULL;
return (new_node);
}
void printList(node* node)
{
while (node != NULL) {
cout << node->data << " " ;
node = node->right;
}
}
int main()
{
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);
node* head = bToDLL(root);
printList(head);
return 0;
}
|
Java
import java.util.Stack;
class Node {
int data;
Node left;
Node right;
public Node( int data) {
this .data = data;
left = null ;
right = null ;
}
}
public class Main {
static Node bToDLL(Node root) {
Stack<Pair<Node, Integer>> s = new Stack<>();
s.push( new Pair<>(root, 0 ));
boolean flag = true ;
Node head = null ;
Node prev = null ;
while (!s.empty()) {
Pair<Node, Integer> x = s.pop();
Node t = x.getKey();
int state = x.getValue();
if (state == 3 || t == null ) {
continue ;
}
s.push( new Pair<>(t, state + 1 ));
if (state == 0 ) {
s.push( new Pair<>(t.left, 0 ));
} else if (state == 1 ) {
if (prev != null ) {
prev.right = t;
}
t.left = prev;
prev = t;
if (flag) {
head = t;
flag = false ;
}
} else if (state == 2 ) {
s.push( new Pair<>(t.right, 0 ));
}
}
return head;
}
static void printList(Node head) {
while (head != null ) {
System.out.print(head.data + " " );
head = head.right;
}
}
public static void main(String[] args)
{
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 );
Node head = bToDLL(root);
printList(head);
}
}
class Pair<K, V> {
private K key;
private V value;
public Pair(K key, V value) {
this .key = key;
this .value = value;
}
public K getKey() {
return key;
}
public V getValue() {
return value;
}
}
|
Python3
def bToDLL(root):
s = []
s.append([root, 0 ])
res = []
flag = True
head = None
prev = None
while len (s) > 0 :
x = s.pop()
t = x[ 0 ]
state = x[ 1 ]
if state = = 3 or t = = None : continue
s.append([t, state + 1 ])
if state = = 0 : s.append([t.left, 0 ])
elif state = = 1 :
if prev ! = None : prev.right = t
t.left = prev
prev = t
if flag:
head = t
flag = False
elif state = = 2 : s.append([t.right, 0 ])
return head
|
C#
using System;
using System.Collections.Generic;
public class Node {
public int data;
public Node left;
public Node right;
public Node( int data)
{
this .data = data;
left = null ;
right = null ;
}
}
public class GFG {
static Node bToDLL(Node root)
{
Stack<KeyValuePair<Node, int > > s
= new Stack<KeyValuePair<Node, int > >();
s.Push( new KeyValuePair<Node, int >(root, 0));
bool flag = true ;
Node head = null ;
Node prev = null ;
while (s.Count != 0) {
KeyValuePair<Node, int > x = s.Pop();
Node t = x.Key;
int state = x.Value;
if (state == 3 || t == null ) {
continue ;
}
s.Push(
new KeyValuePair<Node, int >(t, state + 1));
if (state == 0) {
s.Push(
new KeyValuePair<Node, int >(t.left, 0));
}
else if (state == 1) {
if (prev != null ) {
prev.right = t;
}
t.left = prev;
prev = t;
if (flag) {
head = t;
flag = false ;
}
}
else if (state == 2) {
s.Push( new KeyValuePair<Node, int >(t.right,
0));
}
}
return head;
}
static void printList(Node head)
{
while (head != null ) {
System.Console.Write(head.data + " " );
head = head.right;
}
}
static public void Main()
{
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);
Node head = bToDLL(root);
printList(head);
}
}
|
Javascript
class Node {
constructor(data) {
this .data = data;
this .left = null ;
this .right = null ;
}
}
function bToDLL(root) {
let s = [];
s.push([root, 0]);
let res = [];
let flag = true ;
let head = null ;
let prev = null ;
while (s.length > 0) {
let [t, state] = s.pop();
if (state === 3 || t === null ) continue ;
s.push([t, state + 1]);
if (state === 0) s.push([t.left, 0]);
else if (state === 1) {
if (prev) prev.right = t;
t.left = prev;
prev = t;
if (flag) {
head = t;
flag = false ;
}
} else if (state === 2) s.push([t.right, 0]);
}
return head;
}
function newNode(data) {
let new_node = new Node(data);
return new_node;
}
function printList(node) {
while (node !== null ) {
console.log(node.data);
node = node.right;
}
}
let 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);
let head = bToDLL(root);
printList(head);
|
Time complexity: O(N)
Auxiliary Space: O(N)
Last Updated :
16 Feb, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...