Given the root of a special binary tree with each node containing an additional next pointer, link nodes at the same level using the next pointer in the form of a linked list like structure.

For example, the binary tree on the left should be converted into a binary tree on the right.

 
Link Nodes of Binary Tree

Practice this problem

We can solve this problem in linear time by using hashing. The idea is to traverse the tree in a preorder fashion and store nodes present at each level in a map from left to right. After every node is processed, iterate through the map, and for each level, set the next node for every node present in it.

Following is the C++, Java, and Python program that demonstrates it:

C++


Download  Run Code

Output:

1 —> null
2 —> 3 —> null
4 —> 5 —> 6 —> null
7 —> 8 —> null

Java


Download  Run Code

Output:

1 —> null
2 —> 3 —> null
4 —> 5 —> 6 —> null
7 —> 8 —> null

Python


Download  Run Code

Output:

1 —> None
2 —> 3 —> None
4 —> 5 —> 6 —> None
7 —> 8 —> None

The time complexity of the above solution is O(n), where n is the total number of nodes in the binary tree. The auxiliary space required by the program is O(n) for the unordered map.

How can we solve this using constant space?

The idea is to traverse the tree in a preorder fashion and ensure that all nodes at the current level are linked before all nodes at the next level, i.e., the next pointer of the parent nodes is set before its children.

Then update the next pointer of the parent’s left child to the parent’s right child. If the right child doesn’t exist, link the parent’s left child to the first node in the next level. Similarly, update the next pointer of the parent’s right child to the first node in the next level. If we follow this recursively for the left and right subtrees, we will end up having connected nodes at each level.

Following is the C++, Java, and Python program that demonstrates it:

C++


Download  Run Code

Output:

1 —> null
2 —> 3 —> null
4 —> 5 —> 6 —> null
7 —> 8 —> null

Java


Download  Run Code

Output:

1 —> null
2 —> 3 —> null
4 —> 5 —> 6 —> null
7 —> 8 —> null

Python


Download  Run Code

Output:

1 —> None
2 —> 3 —> None
4 —> 5 —> 6 —> None
7 —> 8 —> None

The time complexity of the above solution is O(n2), where n is the total number of nodes in the binary tree. The solution also takes implicit space for the call stack. We can easily convert the above program into a non-recursive one, which takes O(1) space. The iterative version can be seen here.