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

C++Server Side ProgrammingProgramming

<p>In this tutorial, we will be discussing a program to convert a binary tree to a doubly linked list.</p><p>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.</p><p>For this we are having a very straight forward approach. We will be traversing the binary tree in in order way making the nodes of the doubly linked list along with and finally making the left and right to be the previous and next nodes respectively.</p><h2>Example</h2><p><a class="demo" href="http://tpcg.io/LcuECiVl" rel="nofollow" target="_blank">&nbsp;Live Demo</a></p><pre class="prettyprint notranslate">#include &lt;iostream&gt; using namespace std; //node structure of binary tree struct node{ &nbsp; &nbsp;int data; &nbsp; &nbsp;node* left; &nbsp; &nbsp;node* right; }; //traversing and making nodes for //doubly linked list void binarytodll(node *root, node **head){ &nbsp; &nbsp;if (root == NULL) &nbsp; &nbsp; &nbsp; return; &nbsp; &nbsp;static node* prev = NULL; &nbsp; &nbsp;//converting left subtree &nbsp; &nbsp;binarytodll(root-&gt;left, head); &nbsp; &nbsp;if (prev == NULL) &nbsp; &nbsp; &nbsp; *head = root; &nbsp; &nbsp;else { &nbsp; &nbsp; &nbsp; root-&gt;left = prev; &nbsp; &nbsp; &nbsp; prev-&gt;right = root; &nbsp; &nbsp;} &nbsp; &nbsp;prev = root; &nbsp; &nbsp;//converting right subtree &nbsp; &nbsp;binarytodll(root-&gt;right, head); } //allocating a new node node* newNode(int data) { &nbsp; &nbsp;node* new_node = new node; &nbsp; &nbsp;new_node-&gt;data = data; &nbsp; &nbsp;new_node-&gt;left = new_node-&gt;right = NULL; &nbsp; &nbsp;return (new_node); } //printing nodes of doubly linked list void print_dll(node *node){ &nbsp; &nbsp;while (node!=NULL) { &nbsp; &nbsp; &nbsp; cout &lt;&lt; node-&gt;data &lt;&lt; &quot; &quot;; &nbsp; &nbsp; &nbsp; node = node-&gt;right; &nbsp; &nbsp;} } int main(){ &nbsp; &nbsp;node *root = newNode(10); &nbsp; &nbsp;root-&gt;left = newNode(12); &nbsp; &nbsp;root-&gt;right = newNode(15); &nbsp; &nbsp;root-&gt;left-&gt;left = newNode(25); &nbsp; &nbsp;root-&gt;left-&gt;right = newNode(30); &nbsp; &nbsp;root-&gt;right-&gt;left = newNode(36); &nbsp; &nbsp;node *head = NULL; &nbsp; &nbsp;binarytodll(root, &amp;head); &nbsp; &nbsp;print_dll(head); &nbsp; &nbsp;return 0; }</pre><h2>Output</h2><pre class="result notranslate">25 12 30 10 36 15</pre>
raja
Updated on 06-Jan-2020 11:22:03

Advertisements