> 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](https://1416717093-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-ME49AWTsL3PV5O3FW36%2F-MGlevojx-UeM14ncuyZ%2F-MGlfqyyR-BUVc1TfnTm%2F116_sample.png?alt=media\&token=684a3eae-aa03-45d3-a106-3b1150f1409f)

![Binary Tree](https://1416717093-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-ME49AWTsL3PV5O3FW36%2F-MGlevojx-UeM14ncuyZ%2F-MGlg2Pm2ihT645ZagVY%2F117_sample.png?alt=media\&token=60c24a38-4636-4866-b39d-0aff6afeb424)

### 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
```
