> For the complete documentation index, see [llms.txt](https://soumyajit4419.gitbook.io/ds-algo/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://soumyajit4419.gitbook.io/ds-algo/binary-tree/problems-related-to-binary-trees/populating-next-right-pointers-in-each-node.md).

# 7.Populating Next Right Pointers in Each Node

Given a binary tree. Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to `NULL.`

![Perfect Binary Tree](/files/-MGlfqyyR-BUVc1TfnTm)

![Binary Tree](/files/-MGlg2Pm2ihT645ZagVY)

### Iterative Solution: (using Level Order Traversal)

```cpp
class Solution
{
public:
    Node *connect(Node *root)
    {
        if (root == NULL)
        {
            return root;
        }
        queue<Node *> q;
        q.push(root);
        q.push(NULL);
        Node *t = NULL;

        while (!q.empty())
        {

            t = q.front();
            q.pop();

            if (t != NULL)
            {

                t->next = q.front();

                if (t->left)
                {
                    q.push(t->left);
                }
                if (t->right)
                {
                    q.push(t->right);
                }
            }

            else if (!q.empty())
            {
                q.push(NULL);
            }
        }

        return root;
    }
};
```

**Time Complexity: O(n) , Space Complexity: O(n)**

### Solution II :&#x20;

```cpp
```
