Construct Complete Binary Tree from its Linked List Representation
Last Updated : 19 Sep, 2024
Given the Linked List Representation of a Complete Binary Tree, the task is to construct the complete binary tree. The complete binary tree is represented as a linked list in a way where if the root node is stored at position i, its left, and right children are stored at position 2*i+1, and 2*i+2 respectively.
[Expected Approach] Using Level Order Traversal - O(n) Time and O(n) Space:
We are mainly given level order traversal in sequential form. Head of linked list is always the root of the tree. The first node as root and that the next two nodes are left and right children of root. So we know partial Binary Tree.
The idea is to do Level order traversal of the partially built Binary Tree using queue and traverse the linked list at the same time. At every step, we take the parent node from queue, make next two nodes of linked list as children of the parent node, and push the next two nodes to queue.
Below is the implementation of the above approach:
C++
// C++ program to create a Complete Binary tree// from its Linked List Representation#include<iostream>#include<queue>usingnamespacestd;classLnode{public:intdata;Lnode*next;Lnode(intvalue){data=value;next=nullptr;}};classTnode{public:intdata;Tnode*left;Tnode*right;Tnode(intvalue){data=value;left=right=nullptr;}};// Converts a given linked list representing a complete // binary tree into the linked representation of a binary tree.Tnode*convert(Lnode*head){if(head==nullptr){returnnullptr;}// Queue to store the parent nodesqueue<Tnode*>q;// The first node is always the root node,// and add it to the queueTnode*root=newTnode(head->data);q.push(root);// Move the pointer to the next nodehead=head->next;// Until the end of the linked list is reached, // do the following stepswhile(head){// Take the parent node from the queue // and remove it from the queueTnode*parent=q.front();q.pop();// Take the next two nodes from the linked listTnode*leftChild=nullptr;Tnode*rightChild=nullptr;// Create left childif(head){leftChild=newTnode(head->data);q.push(leftChild);head=head->next;}// Create right childif(head){rightChild=newTnode(head->data);q.push(rightChild);head=head->next;}// Assign the left and right children of the parentparent->left=leftChild;parent->right=rightChild;}returnroot;}// Level Order Traversal of the binary treevoidlevelOrderTraversal(Tnode*root){if(root==nullptr){return;}// Queue to hold nodes at each levelqueue<Tnode*>q;q.push(root);while(!q.empty()){Tnode*currNode=q.front();q.pop();// Print the current node's datacout<<currNode->data<<" ";// Push the left and right children // of the current node to the queueif(currNode->left){q.push(currNode->left);}if(currNode->right){q.push(currNode->right);}}}intmain(){// Create linked list : 10->12->15->25->30->36Lnode*head=newLnode(10);head->next=newLnode(12);head->next->next=newLnode(15);head->next->next->next=newLnode(25);head->next->next->next->next=newLnode(30);head->next->next->next->next->next=newLnode(36);Tnode*root=convert(head);levelOrderTraversal(root);return0;}
Java
// Java program to create a Complete Binary tree// from its Linked List Representationimportjava.util.LinkedList;importjava.util.Queue;classLnode{intdata;Lnodenext;Lnode(intvalue){data=value;next=null;}}classTnode{intdata;Tnodeleft,right;Tnode(intvalue){data=value;left=null;right=null;}}classGfG{// Converts a given linked list representing a complete binary tree into the// linked representation of a binary tree.staticTnodeconvert(Lnodehead){if(head==null){returnnull;}// Queue to store the parent nodesQueue<Tnode>q=newLinkedList<>();// The first node is always the root node,// and add it to the queueTnoderoot=newTnode(head.data);q.add(root);// Move the pointer to the next nodehead=head.next;// Until the end of the linked list is reached,// do the following stepswhile(head!=null){// Take the parent node from the queue// and remove it from the queueTnodeparent=q.poll();TnodeleftChild=null,rightChild=null;// Create left childif(head!=null){leftChild=newTnode(head.data);q.add(leftChild);head=head.next;}// Create right childif(head!=null){rightChild=newTnode(head.data);q.add(rightChild);head=head.next;}// Assign the left and right children of the parentparent.left=leftChild;parent.right=rightChild;}returnroot;}// Level Order Traversal of the binary treestaticvoidlevelOrderTraversal(Tnoderoot){if(root==null){return;}// Queue to hold nodes at each levelQueue<Tnode>q=newLinkedList<>();q.add(root);while(!q.isEmpty()){TnodecurrNode=q.poll();// Print the current node's dataSystem.out.print(currNode.data+" ");// Push the left and right children// of the current node to the queueif(currNode.left!=null){q.add(currNode.left);}if(currNode.right!=null){q.add(currNode.right);}}}publicstaticvoidmain(String[]args){// Create linked list : 10->12->15->25->30->36Lnodehead=newLnode(10);head.next=newLnode(12);head.next.next=newLnode(15);head.next.next.next=newLnode(25);head.next.next.next.next=newLnode(30);head.next.next.next.next.next=newLnode(36);Tnoderoot=convert(head);levelOrderTraversal(root);}}
Python
# Python program to create a Complete Binary tree# from its Linked List RepresentationfromcollectionsimportdequeclassLnode:def__init__(self,value):self.data=valueself.next=NoneclassTnode:def__init__(self,value):self.data=valueself.left=Noneself.right=None# Converts a given linked list representing a complete# binary tree into the linked representation of a binary tree.defconvert(head):ifnothead:returnNone# Queue to store the parent nodesq=deque()# The first node is always the root node,# and add it to the queueroot=Tnode(head.data)q.append(root)# Move the pointer to the next nodehead=head.next# Until the end of the linked list is reached,# do the following stepswhilehead:# Take the parent node from the queue# and remove it from the queueparent=q.popleft()leftChild=NonerightChild=None# Create left childifhead:leftChild=Tnode(head.data)q.append(leftChild)head=head.next# Create right childifhead:rightChild=Tnode(head.data)q.append(rightChild)head=head.next# Assign the left and right children of the parentparent.left=leftChildparent.right=rightChildreturnroot# Level Order Traversal of the binary treedeflevelOrderTraversal(root):ifnotroot:return# Queue to hold nodes at each levelq=deque()q.append(root)whileq:currNode=q.popleft()# Print the current node's dataprint(currNode.data,end=" ")# Push the left and right children# of the current node to the queueifcurrNode.left:q.append(currNode.left)ifcurrNode.right:q.append(currNode.right)if__name__=="__main__":# Create linked list : 10->12->15->25->30->36head=Lnode(10)head.next=Lnode(12)head.next.next=Lnode(15)head.next.next.next=Lnode(25)head.next.next.next.next=Lnode(30)head.next.next.next.next.next=Lnode(36)root=convert(head)levelOrderTraversal(root)
C#
// C# program to create a Complete Binary tree// from its Linked List RepresentationusingSystem;usingSystem.Collections.Generic;classLnode{publicintdata;publicLnodenext;publicLnode(intvalue){data=value;next=null;}}classTnode{publicintdata;publicTnodeleft,right;publicTnode(intvalue){data=value;left=null;right=null;}}classGfG{// Converts a given linked list representing a complete binary tree into the// linked representation of a binary tree.staticTnodeconvert(Lnodehead){if(head==null){returnnull;}// Queue to store the parent nodesQueue<Tnode>q=newQueue<Tnode>();// The first node is always the root node,// and add it to the queueTnoderoot=newTnode(head.data);q.Enqueue(root);// Move the pointer to the next nodehead=head.next;// Until the end of the linked list is reached,// do the following stepswhile(head!=null){// Take the parent node from the queue// and remove it from the queueTnodeparent=q.Dequeue();TnodeleftChild=null,rightChild=null;// Create left childif(head!=null){leftChild=newTnode(head.data);q.Enqueue(leftChild);head=head.next;}// Create right childif(head!=null){rightChild=newTnode(head.data);q.Enqueue(rightChild);head=head.next;}// Assign the left and right children// of the parentparent.left=leftChild;parent.right=rightChild;}returnroot;}// Level Order Traversal of the binary treestaticvoidLevelOrderTraversal(Tnoderoot){if(root==null){return;}// Queue to hold nodes at each levelQueue<Tnode>q=newQueue<Tnode>();q.Enqueue(root);while(q.Count>0){TnodecurrNode=q.Dequeue();// Print the current node's dataConsole.Write(currNode.data+" ");// Push the left and right children// of the current node to the queueif(currNode.left!=null){q.Enqueue(currNode.left);}if(currNode.right!=null){q.Enqueue(currNode.right);}}}staticvoidMain(string[]args){// Create linked list : 10->12->15->25->30->36Lnodehead=newLnode(10);head.next=newLnode(12);head.next.next=newLnode(15);head.next.next.next=newLnode(25);head.next.next.next.next=newLnode(30);head.next.next.next.next.next=newLnode(36);Tnoderoot=convert(head);LevelOrderTraversal(root);}}
JavaScript
// JavaScript program to create a Complete Binary tree// from its Linked List Representation// Linked list node classclassLnode{constructor(value){this.data=value;this.next=null;}}// Binary tree node classclassTnode{constructor(value){this.data=value;this.left=null;this.right=null;}}// Converts a given linked list representing a // complete binary tree into the linked representation of a binary tree.functionconvert(head){if(head===null){returnnull;}// Queue to store the parent nodesletq=[];// The first node is always the root node,// and add it to the queueletroot=newTnode(head.data);q.push(root);// Move the pointer to the next nodehead=head.next;// Until the end of the linked list is reached,// do the following stepswhile(head){// Take the parent node from the queue// and remove it from the queueletparent=q.shift();letleftChild=null;letrightChild=null;// Create left childif(head){leftChild=newTnode(head.data);q.push(leftChild);head=head.next;}// Create right childif(head){rightChild=newTnode(head.data);q.push(rightChild);head=head.next;}// Assign the left and right // children of the parentparent.left=leftChild;parent.right=rightChild;}returnroot;}// Level Order Traversal of the binary treefunctionlevelOrderTraversal(root){if(root===null){return;}// Queue to hold nodes at each levelletq=[];q.push(root);while(q.length>0){letcurrNode=q.shift();// Print the current node's dataconsole.log(currNode.data+" ");// Push the left and right children// of the current node to the queueif(currNode.left){q.push(currNode.left);}if(currNode.right){q.push(currNode.right);}}}// Create linked list : 10->12->15->25->30->36lethead=newLnode(10);head.next=newLnode(12);head.next.next=newLnode(15);head.next.next.next=newLnode(25);head.next.next.next.next=newLnode(30);head.next.next.next.next.next=newLnode(36);letroot=convert(head);levelOrderTraversal(root);
Output
10 12 15 25 30 36
Time Complexity: O(n), where n is the number of nodes. Auxiliary Space: O(n), The queue stores at most n/2 nodes at any point, since for every node processed, its children are added to the queue. Therefore, the maximum space used by the queue is O(n).