# Convert given binary tree to doubly linked list in c#

Csharp program for Convert given binary tree to doubly linked list. Here problem description and explanation.

``````// Include namespace system
using System;
/*
Csharp program for
Convert a given binary tree to doubly linked list
*/
// Binary Tree Node
{
public int data;
{
// Set node value
this.data = data;
this.left = null;
this.right = null;
}
}
public class BinaryTree
{
public BinaryTree()
{
// Set initial values
this.root = null;
}
// Display node element of doubly linked list
public void display()
{
if (this.root == null)
{
}
else
{
// Get first node of linked list
var temp = this.root;
while (temp != null)
{
tail = temp;
// Display node value
Console.Write("  " + temp.data);
// Visit to next node
temp = temp.right;
}
// Get last node of linked list
temp = tail;
while (temp != null)
{
// Display node value
Console.Write("  " + temp.data);
// Visit to prev node
temp = temp.left;
}
}
}
// Function which is convert binary tree to DLL
{
if (node != null)
{
// Visit to left subtree
this.transform(node.left, x, node);
if (this.root == null)
{
// Set the root node when is empty
this.root = node;
}
// Visit to right subtree
this.transform(node.right, node, y);
if (node.left == null)
{
// Connect left node
node.left = x;
if (x != null)
{
// Connect right to left node
x.right = node;
}
}
if (node.right == null)
{
// Connect right node
node.right = y;
if (y != null)
{
// Connect left to right node
y.left = node;
}
}
}
}
public void doublyList()
{
var node = this.root;
if (node != null)
{
// Reset the root value
this.root = null;
// Covert into Doubly linked list
this.transform(node, null, null);
}
}
public static void Main(String[] args)
{
// Create new tree
var tree = new BinaryTree();
/*
Binary Tree
-----------------------
1
/  \
2    3
/    /  \
4    5    6
\    \
7    9
/
8
*/
tree.doublyList();
tree.display();
}
}``````

Output

``````Linked List Head to Tail :
4  8  7  2  1  5  9  3  6