Connect All Siblings of a Binary Tree

Given a binary tree, connect its nodes so that it allows a level-order traversal of the tree.

Statement

The task is to connect all nodes at the same hierarchical level. Connect them from left to right, such that the next pointer of each node points to the node on its immediate right. The next pointer of the right-most node at each level should point to the first node of the next level in the tree.

Each node in the given binary tree for this problem contains the next pointer, along with the left and right pointers. The next pointer is used to connect the same level nodes to each other and across levels.

Example

Consider the following binary tree:

Level up your interview prep. Join Educative to access 80+ hands-on prep courses.