Populating Next Right Pointers in Each Node [C++]
IntuitionThe problem requires us to populate the next pointers in each node of a perfect binary tree. Given the properties of a perfect binary tree, each node h
### Intuition
The problem requires us to populate the `next` pointers in each node of a **perfect binary tree**. Given the properties of a perfect binary tree, each node has either 0 or 2 children, and all leaves are at the same level.

Since each level is **fully populated**, we can use the `next` pointer to traverse each level without needing additional space.

---

### Approach
1. **Start from the Root:** Begin from the leftmost node of the current level.
2. **Iterate Through Nodes on the Current Level:** Use the `next` pointers to traverse through all nodes on the same level.
3. **Connect the Children:**
   - Each node's `left->next` should point to `right`.
   - If the node has a `next` pointer, then `right->next` should point to the `left` child of the node's `next` neighbor.
4. **Move to the Next Level:** Once we finish a level, move to its leftmost node (which is guaranteed to exist in a perfect binary tree).
5. **Repeat Until All Levels are Processed.**

This approach uses constant **O(1) space** by leveraging the `next` pointers instead of an extra data structure (like a queue in BFS).

---

### Complexity Analysis
- **Time Complexity:**  
  - We visit each node exactly **once**, and each operation (assigning `next` pointers) is **O(1)**.
  - Total complexity is **O(n)**.

- **Space Complexity:**  
  - Since we are not using extra memory (like a queue or recursion stack), the space complexity is **O(1)**.

---

### Code
```cpp
class Solution {
public:
    Node* connect(Node* root) {
        if (!root) return nullptr;
        Node* leftMost = root;

        while (leftMost->left) {
            Node* currNode = leftMost;

            while (currNode) {
                currNode->left->next = currNode->right;
                if (currNode->next) {
                    currNode->right->next = currNode->next->left;
                }
                currNode = currNode->next;
            }

            leftMost = leftMost->left;
        }

        return root;
    }
};
```

---

### Explanation of Code
1. **Edge Case:** If the root is `nullptr`, return immediately.
2. **Use `leftMost` to Track the Start of Each Level:**  
   - Since the tree is perfect, we always have a `leftMost->left` if there is a next level.
3. **Traverse the Current Level Using `next` Pointers:**  
   - Assign `left->next = right` for each node.
   - Assign `right->next = next->left` if the node has a `next` pointer.
4. **Move to the Next Level and Repeat.**
['C++']