VOOZH about

URL: https://www.geeksforgeeks.org/dsa/given-linked-list-representation-of-complete-tree-convert-it-to-linked-representation/

⇱ Construct Complete Binary Tree from its Linked List Representation - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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. 

Examples:

Input: 1->2->3>4->5
Output:

👁 Construct-Complete-Binary-Tree-from-its-Linked-List-Representation


Input: 10->12->15->25->30->36
Output:

👁 Construct-Complete-Binary-Tree-from-its-Linked-List-Representation-2

[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:


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).

Comment
Article Tags:
Article Tags: