You are given a binary tree where each node has a next pointer, initially set to NULL. Populate each next pointer to point to its next right node on the same level; if there is no next right node, the next pointer should be set to NULL. Unlike the perfect-tree version, this tree can be any shape. Use only constant extra space (the implicit recursion stack does not count). This catalog task returns, for verification, each level's values read left-to-right by following the next pointers you set.
Example 1
Input: root = [1,2,3,4,5,null,7]
Output: [[1],[2,3],[4,5,7]]
Explanation: Following the next pointers across each level reads 1, then 2 → 3, then 4 → 5 → 7. Node 5 links to 7 even though 3 has no left child in between.
Example 2
Input: root = []
Output: []
Explanation: The tree is empty, so there are no levels.
Example 3
Input: root = [1]
Output: [[1]]
Explanation: The root is the only node on its level, so the single level reads [1].
Once a level is fully linked by next pointers, it behaves exactly like a linked list — you can walk it left to right without any queue. So process the tree one level at a time: while walking the current (already-linked) level, thread its children into the next level using a dummy head. This reuses the next pointers instead of a BFS queue, so the extra space is O(1).
Run checks all cases above. Submit evaluates all test cases.