#include <iostream>
using namespace std;
// Data structure to store a Binary Tree node
struct Node
{
int data;
Node *left, *right, *next;
// constructor
Node(int data)
{
this->data = data;
this->left = this->right = this->next = nullptr;
}
};
// Function to print a given linked list
void printList(Node* head)
{
while (head)
{
cout << head->data << " -> ";
head = head->next;
}
cout << "null" << '\n';
}
// Function to perform inorder traversal of a binary tree where nodes
// at the same level are linked together in the form of a linked list
void inorder(Node* root)
{
if (root == nullptr)
return;
inorder(root->left);
// print current node and its next node
cout << root->data << "->";
if (root->next)
cout << root->next->data << '\n';
else
cout << "null" << '\n';
inorder(root->right);
}
// Iterative function to find the first node in next level of the root node
Node* findNextNode(Node* root)
{
Node* node = root->next;
while (node)
{
// if left child of root's next node exists, return it
if (node->left)
return node->left;
// if right child of root's next node exists, return it
if (node->right)
return node->right;
// if root's next node is a leaf node, recur for root's next node
node = node->next;
}
// all nodes in current level are leaf nodes
return nullptr;
}
// Iterative function to link nodes present in each level of a binary tree
// in the form of a linked list
void linkNodes(Node* root)
{
// base case
if (root == nullptr)
return;
// update next pointer of binary tree nodes level by level from top to bottom
while (root)
{
// get leftmost node in the current level
Node* node = root;
// link all nodes at the current level
while (node)
{
// update the next pointer of root's left child to root's right child
// if right child doesn't exist, link it to first node in the next level
if (root->left) {
root->left->next = (root->right)? root->right: findNextNode(root);
}
// update the next pointer of root's right child to first node
// in the next level
if (root->right) {
root->right->next = findNextNode(root);
}
// advance to the next node in same level
node = node->next;
}
// find leftmost node of the next level for next iteration
if (root->left)
root = root->left;
else if (root->right)
root = root->right;
else
root = findNextNode(root);
}
}
// main function
int main()
{
/* Construct below Tree
1
/ \
2 3
/ \ \
4 5 6
\ /
7 8
*/
Node* root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(4);
root->left->right = new Node(5);
root->right->right = new Node(6);
root->left->left->right = new Node(7);
root->right->right->left = new Node(8);
// link nodes at the same level
linkNodes(root);
// print the nodes
Node* node = root;
while (node)
{
// print current level
printList(node);
// find leftmost node of the the next level
if (node->left)
node = node->left;
else if (node->right)
node = node->right;
else
node = findNextNode(node);
}
// inorder(root);
return 0;
}