---
# System prepended metadata

title: Leetcode 117. Populating Next Right Pointers in Each Node II
tags: [BFS, Queue, Binary Tree, Tree, Leetcode]

---

## 題解

```python=
"""
# Definition for a Node.
class Node:
    def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
        self.val = val
        self.left = left
        self.right = right
        self.next = next
"""

class Solution:
    def connect(self, root: 'Node') -> 'Node':
        queue = [root]

        while queue:
            n = len(queue)
            for i in range(n):
                node = queue.pop(0)
                if node:
                    next_node_index = i + 1
                    if next_node_index < n:
                        node.next = queue[0]
                    else:
                        node.next = None
                    if node.left:
                        queue.append(node.left)
                    if node.right:
                        queue.append(node.right)
        
        return root
```