> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Populating Next Right Pointers in Each Node II

> Tested Python solution for LeetCode 117 with 19 pytest cases. Generate a practice environment with lcpy.

LeetCode 117, [Medium](/catalog/medium). Topics: [Linked List](/catalog/topics/linked-list), [Tree](/catalog/topics/tree), [Depth-First Search](/catalog/topics/depth-first-search), [Breadth-First Search](/catalog/topics/breadth-first-search), [Binary Tree](/catalog/topics/binary-tree). [View on LeetCode](https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/description/).

Generate this problem as a practice environment: tested reference solution, 19 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 117   # by problem number
lcpy gen -s populating_next_right_pointers_in_each_node_ii   # by problem name
```

## Problem

Given a binary tree

```
struct Node {
  int val;
  Node *left;
  Node *right;
  Node *next;
}
```

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

Initially, all next pointers are set to `NULL`.

### Examples

![Example 1](https://assets.leetcode.com/uploads/2019/02/15/117_sample.png)

```
Input: root = [1,2,3,4,5,null,7]
Output: [1,#,2,3,#,4,5,7,#]
Explanation: Given the above binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level.
```

```
Input: root = []
Output: []
```

### Constraints

* The number of nodes in the tree is in the range \[0, 6000]
* -100 \<= Node.val \<= 100

**Follow-up:**

* You may only use constant extra space.
* The recursive approach is fine. You may assume implicit stack space does not count as extra space for this problem.

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/populating_next_right_pointers_in_each_node_ii/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/populating_next_right_pointers_in_each_node_ii/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from __future__ import annotations


class Node:
    def __init__(
        self,
        val: int = 0,
        left: Node | None = None,
        right: Node | None = None,
        next: Node | None = None,
    ):
        self.val = val
        self.left = left
        self.right = right
        self.next = next


class Solution:
    # Time: O(n)
    # Space: O(1)
    def connect(self, root: Node | None) -> Node | None:
        current = root
        while current is not None:
            # Build the next level using the already-linked current level.
            level_head: Node | None = None
            level_tail: Node | None = None
            while current is not None:
                for child in (current.left, current.right):
                    if child is None:
                        continue
                    if level_tail is None:
                        level_head = child
                    else:
                        level_tail.next = child
                    level_tail = child
                current = current.next
            current = level_head
        return root
```

## Complexity

| Time | Space |
| - | - |
| O(n) | O(1) |

## Tags


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.