Given a Binary Tree (BT), the task is to convert it to a Doubly Linked List (DLL) in place. The left and right pointers in nodes will be used as previous and next pointers respectively in converted DLL. The order of nodes in DLL must be the same as the order of the given Binary Tree. The first node of Inorder traversal (leftmost node in BT) must be the head node of the DLL.
Examples:
Input:
Output:
Explanation: The above binary tree is converted into doubly linked list where left pointer of the binary tree node act as the previous node and right pointer of the binary tree node act as the next node.
Input:
Output:
Explanation: The above binary tree is converted into doubly linked list where left pointer of the binary tree node act as the previous node and right pointer of the binary tree node act as the next node.
[Naive Approach] Using Recursion - O(n) Time and O(h) Space
The idea is to recursively traverse the binary tree using inorder traversal. At each node, if left subtree exists, find theinorder predecessor, then process the left subtree and link the current node and predecessor. If right subtree exists, then find theinorder successor, process the right subtree and then link the current node and successor node.
Below is the implementation of the above approach:
C++
// C++ program for in-place// conversion of Binary Tree to DLL#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left;Node*right;Node(intx){data=x;left=nullptr;right=nullptr;}};voidinorder(Node*root){// if left subtree exists if(root->left){// find the inorder predecessor of root nodeNode*pred=root->left;while(pred->right){pred=pred->right;}// process the left subtreeinorder(root->left);// link the predecessor and root nodepred->right=root;root->left=pred;}// if right subtree existsif(root->right){// find the inorder successor of root nodeNode*succ=root->right;while(succ->left){succ=succ->left;}// process the right subtreeinorder(root->right);// link the successor and root noderoot->right=succ;succ->left=root;}}Node*bToDLL(Node*root){// return if root is nullif(root==nullptr)returnroot;// find the head of dllNode*head=root;while(head->left!=nullptr)head=head->left;// recursively convert the tree into dllinorder(root);returnhead;}voidprintList(Node*head){Node*curr=head;while(curr!=NULL){cout<<curr->data<<" ";curr=curr->right;}cout<<endl;}intmain(){// Create a hard coded binary tree// 10// / \ // 12 15 // / \ /// 25 30 36Node*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);return0;}
C
// C program for in-place// conversion of Binary Tree to DLL#include<stdio.h>#include<stdlib.h>structNode{intdata;structNode*left;structNode*right;};// Inorder traversal to link nodesvoidinorder(structNode*root){// if left subtree existsif(root->left){// find the inorder predecessor of root nodestructNode*pred=root->left;while(pred->right){pred=pred->right;}// process the left subtreeinorder(root->left);// link the predecessor and root nodepred->right=root;root->left=pred;}// if right subtree existsif(root->right){// find the inorder successor of root nodestructNode*succ=root->right;while(succ->left){succ=succ->left;}// process the right subtreeinorder(root->right);// link the successor and root noderoot->right=succ;succ->left=root;}}// Function to convert binary tree to doubly linked liststructNode*bToDLL(structNode*root){// return if root is nullif(root==NULL)returnroot;// find the head of dllstructNode*head=root;while(head->left!=NULL)head=head->left;// recursively convert the tree into dllinorder(root);returnhead;}voidprintList(structNode*head){structNode*curr=head;while(curr!=NULL){printf("%d ",curr->data);curr=curr->right;}printf("\n");}structNode*createNode(intx){structNode*node=(structNode*)malloc(sizeof(structNode));node->data=x;node->left=NULL;node->right=NULL;returnnode;}intmain(){// Create a hard coded binary tree// 10// / \ // 12 15 // / \ /// 25 30 36structNode*root=createNode(10);root->left=createNode(12);root->right=createNode(15);root->left->left=createNode(25);root->left->right=createNode(30);root->right->left=createNode(36);structNode*head=bToDLL(root);printList(head);return0;}
Java
// Java program for in-place// conversion of Binary Tree to DLLclassNode{intdata;Nodeleft,right;Node(intx){data=x;left=null;right=null;}}classGfG{// Inorder traversal to link nodesstaticvoidinorder(Noderoot){// if left subtree existsif(root.left!=null){// find the inorder predecessor of root nodeNodepred=root.left;while(pred.right!=null){pred=pred.right;}// process the left subtreeinorder(root.left);// link the predecessor and root nodepred.right=root;root.left=pred;}// if right subtree existsif(root.right!=null){// find the inorder successor of root nodeNodesucc=root.right;while(succ.left!=null){succ=succ.left;}// process the right subtreeinorder(root.right);// link the successor and root noderoot.right=succ;succ.left=root;}}// Function to convert binary tree to doubly linked liststaticNodebToDLL(Noderoot){// return if root is nullif(root==null)returnroot;// find the head of dllNodehead=root;while(head.left!=null)head=head.left;// recursively convert the tree into dllinorder(root);returnhead;}staticvoidprintList(Nodehead){Nodecurr=head;while(curr!=null){System.out.print(curr.data+" ");curr=curr.right;}System.out.println();}publicstaticvoidmain(String[]args){// Create a hard coded binary tree// 10// / \// 12 15 // / \ /// 25 30 36Noderoot=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);Nodehead=bToDLL(root);printList(head);}}
Python
# Python program for in-place# conversion of Binary Tree to DLLclassNode:def__init__(self,new_value):self.data=new_valueself.left=Noneself.right=None# Inorder traversal to link nodesdefinorder(root):# if left subtree existsifroot.left:# find the inorder predecessor of root nodepred=root.leftwhilepred.right:pred=pred.right# process the left subtreeinorder(root.left)# link the predecessor and root nodepred.right=rootroot.left=pred# if right subtree existsifroot.right:# find the inorder successor of root nodesucc=root.rightwhilesucc.left:succ=succ.left# process the right subtreeinorder(root.right)# link the successor and root noderoot.right=succsucc.left=root# Function to convert binary tree to doubly linked listdefbToDLL(root):# return if root is nullifrootisNone:returnroot# find the head of dllhead=rootwhilehead.left:head=head.left# recursively convert the tree into dllinorder(root)returnheaddefprint_list(head):curr=headwhilecurr:print(curr.data,end=" ")curr=curr.rightprint()if__name__=="__main__":# Create a hard coded binary tree# 10# / \# 12 15 # / \ /# 25 30 36root=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=bToDLL(root)print_list(head)
C#
// C# program for in-place// conversion of Binary Tree to DLLusingSystem;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=right=null;}}classGfG{// Inorder traversal to link nodesstaticvoidInorder(Noderoot){// if left subtree existsif(root.left!=null){// find the inorder predecessor of root nodeNodepred=root.left;while(pred.right!=null){pred=pred.right;}// process the left subtreeInorder(root.left);// link the predecessor and root nodepred.right=root;root.left=pred;}// if right subtree existsif(root.right!=null){// find the inorder successor of root nodeNodesucc=root.right;while(succ.left!=null){succ=succ.left;}// process the right subtreeInorder(root.right);// link the successor and root noderoot.right=succ;succ.left=root;}}// Function to convert binary tree to doubly linked liststaticNodeBToDLL(Noderoot){// return if root is nullif(root==null)returnroot;// find the head of dllNodehead=root;while(head.left!=null)head=head.left;// recursively convert the tree into dllInorder(root);returnhead;}staticvoidPrintList(Nodehead){Nodecurr=head;while(curr!=null){Console.Write(curr.data+" ");curr=curr.right;}Console.WriteLine();}staticvoidMain(string[]args){// Create a hard coded binary tree// 10// / \// 12 15 // / \ /// 25 30 36Noderoot=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);Nodehead=BToDLL(root);PrintList(head);}}
JavaScript
// JavaScript program for in-place// conversion of Binary Tree to DLLclassNode{constructor(new_value){this.data=new_value;this.left=null;this.right=null;}}// Inorder traversal to link nodesfunctioninorder(root){// if left subtree existsif(root.left){// find the inorder predecessor of root nodeletpred=root.left;while(pred.right){pred=pred.right;}// process the left subtreeinorder(root.left);// link the predecessor and root nodepred.right=root;root.left=pred;}// if right subtree existsif(root.right){// find the inorder successor of root nodeletsucc=root.right;while(succ.left){succ=succ.left;}// process the right subtreeinorder(root.right);// link the successor and root noderoot.right=succ;succ.left=root;}}// Function to convert binary tree to doubly linked listfunctionbToDLL(root){// return if root is nullif(root===null)returnroot;// find the head of dlllethead=root;while(head.left!==null)head=head.left;// recursively convert the tree into dllinorder(root);returnhead;}functionprintList(head){letcurr=head;while(curr!==null){console.log(curr.data);curr=curr.right;}}// Create a hard coded binary tree// 10// / \// 12 15 // / \ /// 25 30 36letroot=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);lethead=bToDLL(root);printList(head);
Output
25 12 30 10 36 15
Time Complexity: O(n), where n is the number of node in the tree. Auxiliary Space: O(h), where h is the height of tree.
[Expected Approach] Using Morris Traversal Algorithm - O(n) Time and O(1) Space
The idea is to use Morris traversal algorithmto traverse the binary tree, while maintaining proper linkages between the nodes.
Step by step implementation:
Initialize pointers head and tail. head will point to the head node of the resultant dll and tail will point to the last node in dll.
Initialize another pointer curr, which will initially point to root node. Start traversing until curr is not NULL
If curr.left is null, then add the current node to the list (If head is empty, then make this node as head node) and move curr to curr.right.
If curr.left is not null, then find the inorder predecessor of the current node. Let that node be 'pred'. There are two possibilites:
If pred.right is equal to null, then create a link between pred and curr, by setting pred.right = curr and set curr = curr.left.
If pred->right is equal to curr, then this means we have traversed the left subtree and now we can add the curr node to the list. Then set curr = curr->right.
Return the head.
C++
// C++ program for in-place// conversion of Binary Tree to DLL#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left;Node*right;Node(intx){data=x;left=nullptr;right=nullptr;}};// Function to perform Morris Traversal and convert// binary tree to doubly linked list (DLL)Node*morrisTraversal(Node*root){// return if root is nullif(root==nullptr)returnroot;// head and tail node for the dllNode*head=nullptr,*tail=nullptr;Node*curr=root;while(curr!=nullptr){// if left tree does not exists,// then add the curr node to the // dll and set curr = curr->rightif(curr->left==nullptr){if(head==nullptr){head=tail=curr;}else{tail->right=curr;curr->left=tail;tail=curr;}curr=curr->right;}else{Node*pred=curr->left;// find the inorder predecessor while(pred->right!=nullptr&&pred->right!=curr){pred=pred->right;}// create a linkage between pred and// curr if(pred->right==nullptr){pred->right=curr;curr=curr->left;}// if pred->right = curr, it means // we have processed the left subtree,// and we can add curr node to listelse{tail->right=curr;curr->left=tail;tail=curr;curr=curr->right;}}}returnhead;}voidprintList(Node*head){Node*curr=head;while(curr!=nullptr){cout<<curr->data<<" ";curr=curr->right;}cout<<endl;}intmain(){// Create a hard-coded binary tree// 10// / \ // 12 15// / \ /// 25 30 36Node*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=morrisTraversal(root);printList(head);return0;}
C
// C program for in-place// conversion of Binary Tree to DLL#include<stdio.h>#include<stdlib.h>structNode{intdata;structNode*left;structNode*right;};structNode*morrisTraversal(structNode*root){// return if root is nullif(root==NULL)returnroot;// head and tail node for the dllstructNode*head=NULL,*tail=NULL;structNode*curr=root;while(curr!=NULL){// if left tree does not exists,// then add the curr node to the // dll and set curr = curr->rightif(curr->left==NULL){if(head==NULL){head=tail=curr;}else{tail->right=curr;curr->left=tail;tail=curr;}curr=curr->right;}else{structNode*pred=curr->left;// find the inorder predecessor while(pred->right!=NULL&&pred->right!=curr){pred=pred->right;}// create a linkage between pred and// curr if(pred->right==NULL){pred->right=curr;curr=curr->left;}// if pred->right = curr, it means // we have processed the left subtree,// and we can add curr node to listelse{tail->right=curr;curr->left=tail;tail=curr;curr=curr->right;}}}returnhead;}voidprintList(structNode*head){structNode*curr=head;while(curr!=NULL){printf("%d ",curr->data);curr=curr->right;}printf("\n");}structNode*createNode(intnew_value){structNode*node=(structNode*)malloc(sizeof(structNode));node->data=new_value;node->left=node->right=NULL;returnnode;}intmain(){// Create a hard coded binary tree// 10// / \ // 12 15 // / \ /// 25 30 36structNode*root=createNode(10);root->left=createNode(12);root->right=createNode(15);root->left->left=createNode(25);root->left->right=createNode(30);root->right->left=createNode(36);structNode*head=morrisTraversal(root);printList(head);return0;}
Java
// Java program for in-place// conversion of Binary Tree to DLLclassNode{intdata;Nodeleft,right;Node(intx){data=x;left=null;right=null;}}classGfG{staticNodemorrisTraversal(Noderoot){// return if root is nullif(root==null)returnroot;// head and tail node for the dllNodehead=null,tail=null;Nodecurr=root;while(curr!=null){// if left tree does not exists,// then add the curr node to the // dll and set curr = curr.rightif(curr.left==null){if(head==null){head=tail=curr;}else{tail.right=curr;curr.left=tail;tail=curr;}curr=curr.right;}else{Nodepred=curr.left;// find the inorder predecessor while(pred.right!=null&&pred.right!=curr){pred=pred.right;}// create a linkage between pred and// curr if(pred.right==null){pred.right=curr;curr=curr.left;}// if pred.right = curr, it means // we have processed the left subtree,// and we can add curr node to listelse{tail.right=curr;curr.left=tail;tail=curr;curr=curr.right;}}}returnhead;}staticvoidprintList(Nodehead){Nodecurr=head;while(curr!=null){System.out.print(curr.data+" ");curr=curr.right;}System.out.println();}publicstaticvoidmain(String[]args){// Create a hard coded binary tree// 10// / \// 12 15 // / \ /// 25 30 36Noderoot=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);Nodehead=morrisTraversal(root);printList(head);}}
Python
# Python program for in-place# conversion of Binary Tree to DLLclassNode:def__init__(self,new_value):self.data=new_valueself.left=Noneself.right=Nonedefmorris_traversal(root):# return if root is NoneifrootisNone:returnroot# head and tail node for the dllhead=Nonetail=Nonecurr=rootwhilecurrisnotNone:# if left tree does not exist,# then add the curr node to the # dll and set curr = curr.rightifcurr.leftisNone:ifheadisNone:head=tail=currelse:tail.right=currcurr.left=tailtail=currcurr=curr.rightelse:pred=curr.left# find the inorder predecessor whilepred.rightisnotNone \
andpred.right!=curr:pred=pred.right# create a linkage between pred and curr ifpred.rightisNone:pred.right=currcurr=curr.left# if pred.right = curr, it means # we have processed the left subtree,# and we can add curr node to listelse:tail.right=currcurr.left=tailtail=currcurr=curr.rightreturnheaddefprint_list(head):curr=headwhilecurrisnotNone:print(curr.data,end=" ")curr=curr.rightprint()if__name__=="__main__":# Create a hard coded binary tree# 10# / \# 12 15 # / \ /# 25 30 36root=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=morris_traversal(root)print_list(head)
C#
// C# program for in-place// conversion of Binary Tree to DLLusingSystem;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=null;right=null;}}classGfG{staticNodeMorrisTraversal(Noderoot){// return if root is nullif(root==null)returnroot;// head and tail node for the dllNodehead=null,tail=null;Nodecurr=root;while(curr!=null){// if left tree does not exists,// then add the curr node to the // dll and set curr = curr.rightif(curr.left==null){if(head==null){head=tail=curr;}else{tail.right=curr;curr.left=tail;tail=curr;}curr=curr.right;}else{Nodepred=curr.left;// find the inorder predecessor while(pred.right!=null&&pred.right!=curr){pred=pred.right;}// create a linkage between pred and// curr if(pred.right==null){pred.right=curr;curr=curr.left;}// if pred.right = curr, it means // we have processed the left subtree,// and we can add curr node to listelse{tail.right=curr;curr.left=tail;tail=curr;curr=curr.right;}}}returnhead;}staticvoidPrintList(Nodehead){Nodecurr=head;while(curr!=null){Console.Write(curr.data+" ");curr=curr.right;}Console.WriteLine();}staticvoidMain(string[]args){// Create a hard coded binary tree// 10// / \// 12 15 // / \ /// 25 30 36Noderoot=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);Nodehead=MorrisTraversal(root);PrintList(head);}}
JavaScript
// JavaScript program for in-place// conversion of Binary Tree to DLLclassNode{constructor(new_value){this.data=new_value;this.left=this.right=null;}}functionmorrisTraversal(root){// return if root is nullif(root===null)returnroot;// head and tail node for the dlllethead=null,tail=null;letcurr=root;while(curr!==null){// if left tree does not exists,// then add the curr node to the // dll and set curr = curr.rightif(curr.left===null){if(head===null){head=tail=curr;}else{tail.right=curr;curr.left=tail;tail=curr;}curr=curr.right;}else{letpred=curr.left;// find the inorder predecessor while(pred.right!==null&&pred.right!==curr){pred=pred.right;}// create a linkage between pred and curr if(pred.right===null){pred.right=curr;curr=curr.left;}// if pred.right = curr, it means // we have processed the left subtree,// and we can add curr node to listelse{tail.right=curr;curr.left=tail;tail=curr;curr=curr.right;}}}returnhead;}functionprintList(head){letcurr=head;while(curr!==null){console.log(curr.data);curr=curr.right;}}// Create a hard coded binary tree// 10// / \// 12 15 // / \ /// 25 30 36letroot=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);lethead=morrisTraversal(root);printList(head);
Output
25 12 30 10 36 15
Time Complexity: O(n), where n is the number of nodes in tree. Auxiliary Space: O(1)
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.