# Convert a given Binary Tree to Doubly Linked List (Set 2) in C++

In this tutorial, we will be discussing a program to convert a binary tree to a doubly linked list.

For this we will be provided with a binary tree. Our task is to convert it into a doubly linked list such that the left and right pointers become the previous and next pointers. Also the sequential order of the doubly linked list must be equal to the inorder traversal of the binary tree.

For this we are having a different approach. We will be traversing the binary tree in reverse inorder way. Along with we will be creating new nodes and moving the head pointer to the latest one; this will create the doubly linked list from the end to the start.

## Example

Live Demo

#include <stdio.h>
#include <stdlib.h>
//node structure for tree
struct Node{
int data;
Node *left, *right;
};
//converting the binary tree to
if (root == NULL)
return;
//converting right subtree
//inserting the root value to the
//converting left subtree
}
//allocating new node for doubly linked list
Node* newNode(int data){
Node* node = new Node;
node->data = data;
node->left = node->right = NULL;
return node;
}
}
}
int main(){
Node* root = newNode(5);
root->left = newNode(3);
root->right = newNode(6);
root->left->left = newNode(1);
root->left->right = newNode(4);
root->right->right = newNode(8);
root->left->left->left = newNode(0);
root->left->left->right = newNode(2);
root->right->right->left = newNode(7);
root->right->right->right = newNode(9);
return 0;
}

## Output

Doubly Linked list:
0 1 2 3 4 5 6 7 8 9

Updated on: 06-Jan-2020

74 Views