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


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://soumyajit4419.gitbook.io/ds-algo/binary-tree/problems-related-to-binary-trees/populating-next-right-pointers-in-each-node.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
