HTML & JS
#include <bits/stdc++.h>
using namespace std;
struct node {
    int data;
    struct node* left;
    struct node* right;
    struct node* nextRight;
};
void connect(node* root) // using simple iterative level order technique.
{
    queue<node*> q;
    q.push(root);
    node* t = NULL, *prev = root;
    while (!q.empty()) {
        int count = q.size(), flag = 0; // using count to segregate nodes of the same level
        prev->nextRight = NULL; // next of level's last node will be null.
        while (count--) {
            t = q.front();
            q.pop();
            if (flag)
                prev->nextRight = t;
            if (t->left)
                q.push(t->left);
            if (t->right)
                q.push(t->right);
            prev = t;
            flag = 1;
        }
    }
}
struct node* newnode(int data)
{
    struct node* node = (struct node*)
        malloc(sizeof(struct node));
    node->data = data;
    node->left = NULL;
    node->right = NULL;
    node->nextRight = NULL;
 
    return (node);
}
/* Driver program to test above functions*/
int main()
{
    struct node* root = newnode(10);
    root->left = newnode(8);
    root->right = newnode(2);
    root->left->left = newnode(3);
 
    // Populates nextRight pointer in all nodes
    connect(root);
}

Generated URL:

Output:

No Output
Report Bug