Given a linked list, construct a complete binary tree from it. Assume that the order of elements present in the linked list is the same as that in the complete tree’s array representation.

For a tree node at position i in the linked list, the left child is present at position 2×i, and the right child is present at position 2×i + 1. (Here, position i starts from 1).

 
For example, the linked list 1 —> 2 —> 3 —> 4 —> 5 —> 6 should be converted into the following complete binary tree:

       1
     /   \
    2     3
   / \   /
  4   5 6

Practice this problem

Unlike an array, we cannot directly access nodes in the linked list. Therefore, it’s not possible to recursively construct a complete binary tree with a linked list.

Note that the root of the complete binary tree is the head of the linked list and its two children are the next two nodes in the linked list, and each level in a complete binary tree contains consecutive nodes in the linked list.

We know that each level in a complete binary tree is filled except possibly the last, where the nodes are filled from left to right. The idea is to build the complete binary tree level-by-level. Following is a pseudocode for a simple queue-based algorithm using level order traversal:

construct(head):
 
  root —> next_node(head)
  q —> empty queue
  q.enqueue(root)
 
  while (next_node(head))
    node —> q.dequeue()
 
    node.left = next_node(head)
    q.enqueue(node.left)
 
    node.right = next_node(head)
    q.enqueue(node.right)

The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

1 2 4 5 3 6

Java


Download  Run Code

Output:

1 2 4 5 3 6

Python


Download  Run Code

Output:

1 2 4 5 3 6

The time complexity of the above solution is O(n) and requires O(n) extra space, where n is the total number of nodes in the linked list.