Extract Leaves of a Binary Tree in a Doubly Linked List
Last Updated : 8 Sep, 2026
Given a Binary Tree, extract all its leaf nodes from left to right and form a Doubly Linked List (DLL) using the extracted nodes.
Remove the extracted leaf nodes from the original tree while preserving the structure of the remaining tree. Use the left and right pointers of each leaf node as the prev and next pointers of the DLL, respectively.
Note: The output contains the inorder traversal of the modified tree, followed by the DLL traversed from left to right and right to left.
Examples:
Input: root[] = [1, 2, 3, 4, 5, 6, 7]
Output:
Modified Tree : 2 1 3
Doubly Linked List : 4 <-> 5 <-> 6 <-> 7
Explanation: The leaf nodes are modified to form the DLL in-place. Thus their links are removed from the tree.
Input: root[] = [1, 2, 3, 4, 5]
Output: Modified Tree : 2 1
Doubly Linked List: 4 <-> 5 <-> 3
Explanation: The leaf nodes 4, 5, 3 are removed from the tree and linked together to form the DLL from left to right.
[Naive Approach] Collect Leaves, Then Remove - O(n) Time and O(n) Auxiliary Space
The idea is to first collect all leaf nodes, remove them from the tree, and then connect them to form the Doubly Linked List (DLL).
Traverse the tree from left to right and store all leaf nodes in a list.
Traverse the tree again and remove each leaf by setting the corresponding pointer of its parent to null.
Connect the stored leaf nodes in their collected order using their left and right pointers as prev and next, respectively.
Return the first leaf as the head of the DLL.
Since the leaves are collected from left to right, they are already in the required order for the DLL.
C++
#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left;Node*right;Node(intx){data=x;left=right=nullptr;}};vector<Node*>leaves;// Store all leaf nodes from left to right.voidcollectLeaves(Node*node){if(node==nullptr)return;if(node->left==nullptr&&node->right==nullptr){leaves.push_back(node);return;}collectLeaves(node->left);collectLeaves(node->right);}// Remove leaf nodes from the tree.voidremoveLeaves(Node*node){if(node==nullptr)return;if(node->left!=nullptr){if(node->left->left==nullptr&&node->left->right==nullptr){node->left=nullptr;}else{removeLeaves(node->left);}}if(node->right!=nullptr){if(node->right->left==nullptr&&node->right->right==nullptr){node->right=nullptr;}else{removeLeaves(node->right);}}}// Convert leaf nodes into a Doubly Linked List.Node*convertToDLL(Node*root){if(root==nullptr)returnnullptr;if(root->left==nullptr&&root->right==nullptr)returnroot;leaves.clear();// Collect all leaf nodes.collectLeaves(root);// Remove leaf nodes from the tree.removeLeaves(root);// Connect the leaf nodes to form the DLL.for(inti=0;i<leaves.size();i++){leaves[i]->left=(i>0)?leaves[i-1]:nullptr;leaves[i]->right=(i+1<leaves.size())?leaves[i+1]:nullptr;}returnleaves[0];}// Print the modified tree in inorder.voidinorder(Node*root){if(root==nullptr)return;inorder(root->left);cout<<root->data<<" ";inorder(root->right);}// Print DLL from left to right and right to left.voidprintDLL(Node*head){Node*tail=nullptr;cout<<"DLL (Left to Right): ";Node*curr=head;while(curr!=nullptr){cout<<curr->data<<" ";tail=curr;curr=curr->right;}cout<<"\n";cout<<"DLL (Right to Left): ";curr=tail;while(curr!=nullptr){cout<<curr->data<<" ";curr=curr->left;}cout<<"\n";}intmain(){/* 1 / \ 2 3 / \ / \ 4 5 6 7 */Node*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->left->left=newNode(4);root->left->right=newNode(5);root->right->left=newNode(6);root->right->right=newNode(7);Node*head=convertToDLL(root);cout<<"Modified Tree (Inorder): ";inorder(root);cout<<"\n";printDLL(head);return0;}
Java
importjava.util.ArrayList;classNode{intdata;Nodeleft;Noderight;Node(intx){data=x;left=right=null;}}classGFG{staticArrayList<Node>leaves=newArrayList<>();// Store all leaf nodes from left to right.staticvoidcollectLeaves(Nodenode){if(node==null)return;if(node.left==null&&node.right==null){leaves.add(node);return;}collectLeaves(node.left);collectLeaves(node.right);}// Remove leaf nodes from the tree.staticvoidremoveLeaves(Nodenode){if(node==null)return;if(node.left!=null){if(node.left.left==null&&node.left.right==null){node.left=null;}else{removeLeaves(node.left);}}if(node.right!=null){if(node.right.left==null&&node.right.right==null){node.right=null;}else{removeLeaves(node.right);}}}// Convert leaf nodes into a Doubly Linked List.staticNodeconvertToDLL(Noderoot){if(root==null)returnnull;if(root.left==null&&root.right==null)returnroot;leaves.clear();// Collect all leaf nodes.collectLeaves(root);// Remove leaf nodes from the tree.removeLeaves(root);// Connect the leaf nodes to form the DLL.for(inti=0;i<leaves.size();i++){leaves.get(i).left=(i>0)?leaves.get(i-1):null;leaves.get(i).right=(i+1<leaves.size())?leaves.get(i+1):null;}returnleaves.get(0);}// Print the modified tree in inorder.staticvoidinorder(Noderoot){if(root==null)return;inorder(root.left);System.out.print(root.data+" ");inorder(root.right);}// Print DLL from left to right and right to left.staticvoidprintDLL(Nodehead){Nodetail=null;System.out.print("DLL (Left to Right): ");Nodecurr=head;while(curr!=null){System.out.print(curr.data+" ");tail=curr;curr=curr.right;}System.out.println();System.out.print("DLL (Right to Left): ");curr=tail;while(curr!=null){System.out.print(curr.data+" ");curr=curr.left;}System.out.println();}publicstaticvoidmain(String[]args){/* 1 / \ 2 3 / \ / \ 4 5 6 7 */Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.left=newNode(6);root.right.right=newNode(7);Nodehead=convertToDLL(root);System.out.print("Modified Tree (Inorder): ");inorder(root);System.out.println();printDLL(head);}}
Python
classNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# Store all leaf nodes from left to right.defcollectLeaves(node,leaves):ifnodeisNone:returnifnode.leftisNoneandnode.rightisNone:leaves.append(node)returncollectLeaves(node.left,leaves)collectLeaves(node.right,leaves)# Remove leaf nodes from the tree.defremoveLeaves(node):ifnodeisNone:returnifnode.leftisnotNone:ifnode.left.leftisNoneandnode.left.rightisNone:node.left=Noneelse:removeLeaves(node.left)ifnode.rightisnotNone:ifnode.right.leftisNoneandnode.right.rightisNone:node.right=Noneelse:removeLeaves(node.right)# Convert leaf nodes into a Doubly Linked List.defconvertToDLL(root):ifrootisNone:returnNoneifroot.leftisNoneandroot.rightisNone:returnrootleaves=[]# Collect all leaf nodes.collectLeaves(root,leaves)# Remove leaf nodes from the tree.removeLeaves(root)# Connect the leaf nodes to form the DLL.foriinrange(len(leaves)):leaves[i].left=leaves[i-1]ifi>0elseNoneleaves[i].right=leaves[i+1]ifi+1<len(leaves)elseNonereturnleaves[0]# Print the modified tree in inorder.definorder(root):ifrootisNone:returninorder(root.left)print(root.data,end=" ")inorder(root.right)# Print DLL from left to right and right to left.defprintDLL(head):tail=Noneprint("DLL (Left to Right): ",end="")curr=headwhilecurrisnotNone:print(curr.data,end=" ")tail=currcurr=curr.rightprint()print("DLL (Right to Left): ",end="")curr=tailwhilecurrisnotNone:print(curr.data,end=" ")curr=curr.leftprint()if__name__=="__main__":""" 1 / \ 2 3 / \ / \ 4 5 6 7 """root=Node(1)root.left=Node(2)root.right=Node(3)root.left.left=Node(4)root.left.right=Node(5)root.right.left=Node(6)root.right.right=Node(7)head=convertToDLL(root)print("Modified Tree (Inorder): ",end="")inorder(root)print()printDLL(head)
C#
usingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intx){data=x;left=right=null;}}classGFG{staticList<Node>leaves=newList<Node>();// Store all leaf nodes from left to right.staticvoidcollectLeaves(Nodenode){if(node==null)return;if(node.left==null&&node.right==null){leaves.Add(node);return;}collectLeaves(node.left);collectLeaves(node.right);}// Remove leaf nodes from the tree.staticvoidremoveLeaves(Nodenode){if(node==null)return;if(node.left!=null){if(node.left.left==null&&node.left.right==null){node.left=null;}else{removeLeaves(node.left);}}if(node.right!=null){if(node.right.left==null&&node.right.right==null){node.right=null;}else{removeLeaves(node.right);}}}// Convert leaf nodes into a Doubly Linked List.staticNodeconvertToDLL(Noderoot){if(root==null)returnnull;if(root.left==null&&root.right==null)returnroot;leaves.Clear();// Collect all leaf nodes.collectLeaves(root);// Remove leaf nodes from the tree.removeLeaves(root);// Connect the leaf nodes to form the DLL.for(inti=0;i<leaves.Count;i++){leaves[i].left=i>0?leaves[i-1]:null;leaves[i].right=i+1<leaves.Count?leaves[i+1]:null;}returnleaves[0];}// Print the modified tree in inorder.staticvoidinorder(Noderoot){if(root==null)return;inorder(root.left);Console.Write(root.data+" ");inorder(root.right);}// Print DLL from left to right and right to left.staticvoidprintDLL(Nodehead){Nodetail=null;Console.Write("DLL (Left to Right): ");Nodecurr=head;while(curr!=null){Console.Write(curr.data+" ");tail=curr;curr=curr.right;}Console.WriteLine();Console.Write("DLL (Right to Left): ");curr=tail;while(curr!=null){Console.Write(curr.data+" ");curr=curr.left;}Console.WriteLine();}staticvoidMain(){/* 1 / \ 2 3 / \ / \ 4 5 6 7 */Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.left=newNode(6);root.right.right=newNode(7);Nodehead=convertToDLL(root);Console.Write("Modified Tree (Inorder): ");inorder(root);Console.WriteLine();printDLL(head);}}
JavaScript
classNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// Store all leaf nodes from left to right.functioncollectLeaves(node,leaves){if(node===null)return;if(node.left===null&&node.right===null){leaves.push(node);return;}collectLeaves(node.left,leaves);collectLeaves(node.right,leaves);}// Remove leaf nodes from the tree.functionremoveLeaves(node){if(node===null)return;if(node.left!==null){if(node.left.left===null&&node.left.right===null){node.left=null;}else{removeLeaves(node.left);}}if(node.right!==null){if(node.right.left===null&&node.right.right===null){node.right=null;}else{removeLeaves(node.right);}}}// Convert leaf nodes into a Doubly Linked List.functionconvertToDLL(root){if(root===null)returnnull;if(root.left===null&&root.right===null)returnroot;letleaves=[];// Collect all leaf nodes.collectLeaves(root,leaves);// Remove leaf nodes from the tree.removeLeaves(root);// Connect the leaf nodes to form the DLL.for(leti=0;i<leaves.length;i++){leaves[i].left=i>0?leaves[i-1]:null;leaves[i].right=i+1<leaves.length?leaves[i+1]:null;}returnleaves[0];}// Print the modified tree in inorder.functioninorder(root){if(root===null)return;inorder(root.left);process.stdout.write(root.data+" ");inorder(root.right);}// Print DLL from left to right and right to left.functionprintDLL(head){lettail=null;process.stdout.write("DLL (Left to Right): ");letcurr=head;while(curr!==null){process.stdout.write(curr.data+" ");tail=curr;curr=curr.right;}console.log();process.stdout.write("DLL (Right to Left): ");curr=tail;while(curr!==null){process.stdout.write(curr.data+" ");curr=curr.left;}console.log();}/* 1 / \ 2 3 / \ / \ 4 5 6 7*/letroot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.left=newNode(6);root.right.right=newNode(7);lethead=convertToDLL(root);process.stdout.write("Modified Tree (Inorder): ");inorder(root);console.log();printDLL(head);
Output
Modified Tree (Inorder): 2 1 3
DLL (Left to Right): 4 5 6 7
DLL (Right to Left): 7 6 5 4
[Better Approach] Recursion with Parent Tracking - O(n) Time and O(h) Auxiliary Space
Instead of storing the leaf nodes separately, process each leaf as soon as it is encountered.
The recursive function keeps track of the parent node and whether the current node is its left or right child. This allows the leaf to be removed immediately while it is added to the DLL.
Initialize head and tail as null.
Traverse the tree from left to right while keeping track of the parent.
If the current node is a leaf, detach it from its parent and add it to the DLL.
Otherwise, recursively process its left and right subtrees.
Return head as the head of the DLL.
Since the tree is traversed from left to right, the leaf nodes are added to the DLL in the same order.
Consider the following Binary Tree:
Initially: head = nullptr, tail = nullptr
The traversal starts from the root and moves from left to right.
Node 1 is not a leaf, so recursively process its left subtree.
Node 2 is not a leaf, so process its left child.
Visit 4: It is a leaf. Detach it from 2 and add it to the DLL.
4
Visit 5: Detach it from 2 and connect it after 4.
4 <-> 5
Visit 6: Detach it from 3 and connect it after 5.
4 <-> 5 <-> 6
Visit 7: Detach it from 3 and connect it after 6.
4 <-> 5 <-> 6 <-> 7
After the traversal, the modified tree is:
And the final DLL is: 4 <-> 5 <-> 6 <-> 7
Thus, each original leaf is removed from the tree and added to the DLL in left-to-right order.
C++
#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left;Node*right;Node(intx){data=x;left=right=nullptr;}};Node*head=nullptr;Node*tail=nullptr;// Convert leaf nodes into a Doubly Linked List.voidconvertToDLLUtil(Node*node,Node*parent,boolisLeftChild){if(node==nullptr)return;// If the node is a leaf, remove it and add it to the DLL.if(node->left==nullptr&&node->right==nullptr){if(parent!=nullptr){if(isLeftChild)parent->left=nullptr;elseparent->right=nullptr;}// Add the leaf to the DLL.if(head==nullptr){head=node;}else{tail->right=node;node->left=tail;}tail=node;return;}convertToDLLUtil(node->left,node,true);convertToDLLUtil(node->right,node,false);}// Convert all leaf nodes of the tree into a DLL.Node*convertToDLL(Node*root){if(root==nullptr)returnnullptr;if(root->left==nullptr&&root->right==nullptr)returnroot;head=nullptr;tail=nullptr;convertToDLLUtil(root,nullptr,false);returnhead;}// Print the modified tree in inorder.voidinorder(Node*root){if(root==nullptr)return;inorder(root->left);cout<<root->data<<" ";inorder(root->right);}// Print DLL from left to right and right to left.voidprintDLL(Node*head){Node*curr=head;Node*tail=nullptr;cout<<"DLL (Left to Right): ";while(curr!=nullptr){cout<<curr->data<<" ";tail=curr;curr=curr->right;}cout<<"\n";cout<<"DLL (Right to Left): ";curr=tail;while(curr!=nullptr){cout<<curr->data<<" ";curr=curr->left;}cout<<"\n";}intmain(){/* 1 / \ 2 3 / \ / \ 4 5 6 7 */Node*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->left->left=newNode(4);root->left->right=newNode(5);root->right->left=newNode(6);root->right->right=newNode(7);Node*head=convertToDLL(root);cout<<"Modified Tree (Inorder): ";inorder(root);cout<<"\n";printDLL(head);return0;}
Java
classNode{intdata;Nodeleft;Noderight;Node(intx){data=x;left=right=null;}}classGFG{staticNodehead=null;staticNodetail=null;// Convert leaf nodes into a Doubly Linked List.staticvoidconvertToDLLUtil(Nodenode,Nodeparent,booleanisLeftChild){if(node==null)return;// If the node is a leaf, remove it and add it to the DLL.if(node.left==null&&node.right==null){if(parent!=null){if(isLeftChild)parent.left=null;elseparent.right=null;}// Add the leaf to the DLL.if(head==null){head=node;}else{tail.right=node;node.left=tail;}tail=node;return;}convertToDLLUtil(node.left,node,true);convertToDLLUtil(node.right,node,false);}// Convert all leaf nodes of the tree into a DLL.staticNodeconvertToDLL(Noderoot){if(root==null)returnnull;if(root.left==null&&root.right==null)returnroot;head=null;tail=null;convertToDLLUtil(root,null,false);returnhead;}// Print the modified tree in inorder.staticvoidinorder(Noderoot){if(root==null)return;inorder(root.left);System.out.print(root.data+" ");inorder(root.right);}// Print DLL from left to right and right to left.staticvoidprintDLL(Nodehead){Nodecurr=head;Nodetail=null;System.out.print("DLL (Left to Right): ");while(curr!=null){System.out.print(curr.data+" ");tail=curr;curr=curr.right;}System.out.println();System.out.print("DLL (Right to Left): ");curr=tail;while(curr!=null){System.out.print(curr.data+" ");curr=curr.left;}System.out.println();}publicstaticvoidmain(String[]args){/* 1 / \ 2 3 / \ / \ 4 5 6 7 */Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.left=newNode(6);root.right.right=newNode(7);Nodehead=convertToDLL(root);System.out.print("Modified Tree (Inorder): ");inorder(root);System.out.println();printDLL(head);}}
Python
classNode:def__init__(self,x):self.data=xself.left=Noneself.right=Nonehead=Nonetail=None# Convert leaf nodes into a Doubly Linked List.defconvertToDLLUtil(node,parent,isLeftChild):globalhead,tailifnodeisNone:return# If the node is a leaf, remove it and add it to the DLL.ifnode.leftisNoneandnode.rightisNone:ifparentisnotNone:ifisLeftChild:parent.left=Noneelse:parent.right=None# Add the leaf to the DLL.ifheadisNone:head=nodeelse:tail.right=nodenode.left=tailtail=nodereturnconvertToDLLUtil(node.left,node,True)convertToDLLUtil(node.right,node,False)# Convert all leaf nodes of the tree into a DLL.defconvertToDLL(root):globalhead,tailifrootisNone:returnNoneifroot.leftisNoneandroot.rightisNone:returnroothead=Nonetail=NoneconvertToDLLUtil(root,None,False)returnhead# Print the modified tree in inorder.definorder(root):ifrootisNone:returninorder(root.left)print(root.data,end=" ")inorder(root.right)# Print DLL from left to right and right to left.defprintDLL(head):curr=headtail=Noneprint("DLL (Left to Right): ",end="")whilecurrisnotNone:print(curr.data,end=" ")tail=currcurr=curr.rightprint()print("DLL (Right to Left): ",end="")curr=tailwhilecurrisnotNone:print(curr.data,end=" ")curr=curr.leftprint()if__name__=="__main__":""" 1 / \ 2 3 / \ / \ 4 5 6 7 """root=Node(1)root.left=Node(2)root.right=Node(3)root.left.left=Node(4)root.left.right=Node(5)root.right.left=Node(6)root.right.right=Node(7)head=convertToDLL(root)print("Modified Tree (Inorder): ",end="")inorder(root)print()printDLL(head)
C#
usingSystem;classNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intx){data=x;left=right=null;}}classGFG{staticNodehead=null;staticNodetail=null;// Convert leaf nodes into a Doubly Linked List.staticvoidconvertToDLLUtil(Nodenode,Nodeparent,boolisLeftChild){if(node==null)return;// If the node is a leaf, remove it and add it to the DLL.if(node.left==null&&node.right==null){if(parent!=null){if(isLeftChild)parent.left=null;elseparent.right=null;}// Add the leaf to the DLL.if(head==null){head=node;}else{tail.right=node;node.left=tail;}tail=node;return;}convertToDLLUtil(node.left,node,true);convertToDLLUtil(node.right,node,false);}// Convert all leaf nodes of the tree into a DLL.staticNodeconvertToDLL(Noderoot){if(root==null)returnnull;if(root.left==null&&root.right==null)returnroot;head=null;tail=null;convertToDLLUtil(root,null,false);returnhead;}// Print the modified tree in inorder.staticvoidinorder(Noderoot){if(root==null)return;inorder(root.left);Console.Write(root.data+" ");inorder(root.right);}// Print DLL from left to right and right to left.staticvoidprintDLL(Nodehead){Nodecurr=head;Nodetail=null;Console.Write("DLL (Left to Right): ");while(curr!=null){Console.Write(curr.data+" ");tail=curr;curr=curr.right;}Console.WriteLine();Console.Write("DLL (Right to Left): ");curr=tail;while(curr!=null){Console.Write(curr.data+" ");curr=curr.left;}Console.WriteLine();}staticvoidMain(){/* 1 / \ 2 3 / \ / \ 4 5 6 7 */Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.left=newNode(6);root.right.right=newNode(7);Nodehead=convertToDLL(root);Console.Write("Modified Tree (Inorder): ");inorder(root);Console.WriteLine();printDLL(head);}}
JavaScript
classNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// Convert leaf nodes into a Doubly Linked List.functionconvertToDLLUtil(node,parent,isLeftChild,list){if(node===null)return;// If the node is a leaf, remove it and add it to the DLL.if(node.left===null&&node.right===null){if(parent!==null){if(isLeftChild)parent.left=null;elseparent.right=null;}// Add the leaf to the DLL.if(list.head===null){list.head=node;}else{list.tail.right=node;node.left=list.tail;}list.tail=node;return;}convertToDLLUtil(node.left,node,true,list);convertToDLLUtil(node.right,node,false,list);}// Convert all leaf nodes of the tree into a DLL.functionconvertToDLL(root){if(root===null)returnnull;if(root.left===null&&root.right===null)returnroot;letlist={head:null,tail:null};convertToDLLUtil(root,null,false,list);returnlist.head;}// Print the modified tree in inorder.functioninorder(root){if(root===null)return;inorder(root.left);process.stdout.write(root.data+" ");inorder(root.right);}// Print DLL from left to right and right to left.functionprintDLL(head){letcurr=head;lettail=null;process.stdout.write("DLL (Left to Right): ");while(curr!==null){process.stdout.write(curr.data+" ");tail=curr;curr=curr.right;}console.log();process.stdout.write("DLL (Right to Left): ");curr=tail;while(curr!==null){process.stdout.write(curr.data+" ");curr=curr.left;}console.log();}// Driver code/* 1 / \ 2 3 / \ / \ 4 5 6 7 */letroot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.left=newNode(6);root.right.right=newNode(7);lethead=convertToDLL(root);process.stdout.write("Modified Tree (Inorder): ");inorder(root);console.log();printDLL(head);
Output
Modified Tree (Inorder): 2 1 3
DLL (Left to Right): 4 5 6 7
DLL (Right to Left): 7 6 5 4
[Expected Approach] Recursion with Modified Subtree - O(n) Time and O(h) Auxiliary Space
The idea is to let the recursive function return the modified subtree after processing it.
If the current node is a leaf, add it to the DLL and return nullptr. The parent then assigns this nullptr to its child pointer, automatically removing the leaf from the tree.
For a non-leaf node, recursively process both subtrees, update its child pointers, and return the current node.
Since the left subtree is processed before the right subtree, the DLL maintains the left-to-right order of the original leaf nodes.
Consider the following Binary Tree:
Initially, both head and tail are nullptr.
The tree is traversed from left to right. Whenever a leaf node is found, it is added to the DLL and nullptr is returned to its parent. This removes the leaf from the tree.
Visit 4:
It is a leaf, so add it to the DLL.
DLL: 4
Node 2 removes 4 from its left child.
Visit 5:
It is a leaf, so add it after 4.
DLL: 4 <-> 5
Node 2 removes 5 from its right child.
Visit 6:
It is a leaf, so add it after 5.
DLL: 4 <-> 5 <-> 6
Node 3 removes 6 from its left child.
Visit 7:
It is a leaf, so add it after 6.
DLL: 4 <-> 5 <-> 6 <-> 7
Node 3 removes 7 from its right child.
After processing all nodes, the remaining tree is:
The final DLL is: 4 <-> 5 <-> 6 <-> 7
Thus, all original leaf nodes are removed from the tree and connected into a DLL while preserving their left-to-right order.
C++
#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left;Node*right;Node(intx){data=x;left=right=nullptr;}};Node*head=nullptr;Node*tail=nullptr;// Convert leaf nodes into a Doubly Linked List.Node*convertToDLLUtil(Node*node){if(node==nullptr)returnnullptr;// If the node is a leaf, remove it and add it to the DLL.if(node->left==nullptr&&node->right==nullptr){// Add the leaf to the DLL.if(head==nullptr){head=node;}else{tail->right=node;node->left=tail;}tail=node;returnnullptr;}node->left=convertToDLLUtil(node->left);node->right=convertToDLLUtil(node->right);returnnode;}// Convert all leaf nodes of the tree into a DLL.Node*convertToDLL(Node*root){if(root==nullptr)returnnullptr;head=nullptr;tail=nullptr;root=convertToDLLUtil(root);returnhead;}// Print the modified tree in inorder.voidinorder(Node*root){if(root==nullptr)return;inorder(root->left);cout<<root->data<<" ";inorder(root->right);}// Print DLL from left to right and right to left.voidprintDLL(Node*head){Node*curr=head;Node*tail=nullptr;cout<<"DLL (Left to Right): ";while(curr!=nullptr){cout<<curr->data<<" ";tail=curr;curr=curr->right;}cout<<"\n";cout<<"DLL (Right to Left): ";curr=tail;while(curr!=nullptr){cout<<curr->data<<" ";curr=curr->left;}cout<<"\n";}intmain(){/* 1 / \ 2 3 / \ / \ 4 5 6 7 */Node*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->left->left=newNode(4);root->left->right=newNode(5);root->right->left=newNode(6);root->right->right=newNode(7);Node*head=convertToDLL(root);cout<<"Modified Tree (Inorder): ";inorder(root);cout<<"\n";printDLL(head);return0;}
Java
classNode{intdata;Nodeleft;Noderight;Node(intx){data=x;left=right=null;}}publicclassGFG{staticNodehead=null;staticNodetail=null;// Convert leaf nodes into a Doubly Linked List.staticNodeconvertToDLLUtil(Nodenode){if(node==null)returnnull;// If the node is a leaf, remove it and add it to the DLL.if(node.left==null&&node.right==null){// Add the leaf to the DLL.if(head==null){head=node;}else{tail.right=node;node.left=tail;}tail=node;returnnull;}node.left=convertToDLLUtil(node.left);node.right=convertToDLLUtil(node.right);returnnode;}// Convert all leaf nodes of the tree into a DLL.staticNodeconvertToDLL(Noderoot){if(root==null)returnnull;head=null;tail=null;root=convertToDLLUtil(root);returnhead;}// Print the modified tree in inorder.staticvoidinorder(Noderoot){if(root==null)return;inorder(root.left);System.out.print(root.data+" ");inorder(root.right);}// Print DLL from left to right and right to left.staticvoidprintDLL(Nodehead){Nodecurr=head;Nodetail=null;System.out.print("DLL (Left to Right): ");while(curr!=null){System.out.print(curr.data+" ");tail=curr;curr=curr.right;}System.out.println();System.out.print("DLL (Right to Left): ");curr=tail;while(curr!=null){System.out.print(curr.data+" ");curr=curr.left;}System.out.println();}publicstaticvoidmain(String[]args){/* 1 / \ 2 3 / \ / \ 4 5 6 7 */Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.left=newNode(6);root.right.right=newNode(7);Nodehead=convertToDLL(root);System.out.print("Modified Tree (Inorder): ");inorder(root);System.out.println();printDLL(head);}}
Python
classNode:def__init__(self,x):self.data=xself.left=Noneself.right=Nonehead=Nonetail=None# Convert leaf nodes into a Doubly Linked List.defconvertToDLLUtil(node):globalhead,tailifnodeisNone:returnNone# If the node is a leaf, remove it and add it to the DLL.ifnode.leftisNoneandnode.rightisNone:# Add the leaf to the DLL.ifheadisNone:head=nodeelse:tail.right=nodenode.left=tailtail=nodereturnNonenode.left=convertToDLLUtil(node.left)node.right=convertToDLLUtil(node.right)returnnode# Convert all leaf nodes of the tree into a DLL.defconvertToDLL(root):globalhead,tailifrootisNone:returnNonehead=Nonetail=Noneroot=convertToDLLUtil(root)returnhead# Print the modified tree in inorder.definorder(root):ifrootisNone:returninorder(root.left)print(root.data,end=" ")inorder(root.right)# Print DLL from left to right and right to left.defprintDLL(head):curr=headtail=Noneprint("DLL (Left to Right): ",end="")whilecurrisnotNone:print(curr.data,end=" ")tail=currcurr=curr.rightprint()print("DLL (Right to Left): ",end="")curr=tailwhilecurrisnotNone:print(curr.data,end=" ")curr=curr.leftprint()defmain():""" 1 / \ 2 3 / \ / \ 4 5 6 7 """root=Node(1)root.left=Node(2)root.right=Node(3)root.left.left=Node(4)root.left.right=Node(5)root.right.left=Node(6)root.right.right=Node(7)head=convertToDLL(root)print("Modified Tree (Inorder): ",end="")inorder(root)print()printDLL(head)if__name__=="__main__":main()
C#
usingSystem;classNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intx){data=x;left=right=null;}}classProgram{staticNodehead=null;staticNodetail=null;// Convert leaf nodes into a Doubly Linked List.staticNodeconvertToDLLUtil(Nodenode){if(node==null)returnnull;// If the node is a leaf, remove it and add it to the DLL.if(node.left==null&&node.right==null){// Add the leaf to the DLL.if(head==null){head=node;}else{tail.right=node;node.left=tail;}tail=node;returnnull;}node.left=convertToDLLUtil(node.left);node.right=convertToDLLUtil(node.right);returnnode;}// Convert all leaf nodes of the tree into a DLL.staticNodeconvertToDLL(Noderoot){if(root==null)returnnull;head=null;tail=null;root=convertToDLLUtil(root);returnhead;}// Print the modified tree in inorder.staticvoidinorder(Noderoot){if(root==null)return;inorder(root.left);Console.Write(root.data+" ");inorder(root.right);}// Print DLL from left to right and right to left.staticvoidprintDLL(Nodehead){Nodecurr=head;Nodetail=null;Console.Write("DLL (Left to Right): ");while(curr!=null){Console.Write(curr.data+" ");tail=curr;curr=curr.right;}Console.WriteLine();Console.Write("DLL (Right to Left): ");curr=tail;while(curr!=null){Console.Write(curr.data+" ");curr=curr.left;}Console.WriteLine();}staticvoidMain(){/* 1 / \ 2 3 / \ / \ 4 5 6 7 */Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.left=newNode(6);root.right.right=newNode(7);Nodehead=convertToDLL(root);Console.Write("Modified Tree (Inorder): ");inorder(root);Console.WriteLine();printDLL(head);}}
JavaScript
classNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// Convert leaf nodes into a Doubly Linked List.functionconvertToDLLUtil(node,list){if(node===null)returnnull;// If the node is a leaf, remove it and add it to the DLL.if(node.left===null&&node.right===null){// Add the leaf to the DLL.if(list.head===null){list.head=node;}else{list.tail.right=node;node.left=list.tail;}list.tail=node;returnnull;}node.left=convertToDLLUtil(node.left,list);node.right=convertToDLLUtil(node.right,list);returnnode;}// Convert all leaf nodes of the tree into a DLL.functionconvertToDLL(root){if(root===null)returnnull;letlist={head:null,tail:null};root=convertToDLLUtil(root,list);returnlist.head;}// Print the modified tree in inorder.functioninorder(root){if(root===null)return;inorder(root.left);process.stdout.write(root.data+" ");inorder(root.right);}// Print DLL from left to right and right to left.functionprintDLL(head){letcurr=head;lettail=null;process.stdout.write("DLL (Left to Right): ");while(curr!==null){process.stdout.write(curr.data+" ");tail=curr;curr=curr.right;}console.log();process.stdout.write("DLL (Right to Left): ");curr=tail;while(curr!==null){process.stdout.write(curr.data+" ");curr=curr.left;}console.log();}// Driver code/* 1 / \ 2 3 / \ / \ 4 5 6 7 */letroot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.left=newNode(6);root.right.right=newNode(7);lethead=convertToDLL(root);process.stdout.write("Modified Tree (Inorder): ");inorder(root);console.log();printDLL(head);
Output
Modified Tree (Inorder): 2 1 3
DLL (Left to Right): 4 5 6 7
DLL (Right to Left): 7 6 5 4