Populating Next Right Pointers in Each Node II
Populating Next Right Pointers in Each Node II
Given a binary tree (not necessarily perfect), connect each node's Next pointer to its next right node in the same level. If there is no next right node, set Next to nil. Return the root.
Function signature
func Connect(root *Node) *Node
Inputs / outputs
root: root of the tree.- Return: root, after linking
Nextpointers.
Example
1
/ \
2 3
/ \ \
4 5 7
Level links:
1 -> nil
2 -> 3 -> nil
4 -> 5 -> 7 -> nil
Constraints
- 0 <= number of nodes <= 100_000
Core idea (near-solution)
Do a level-order traversal. For each level, wire nodes in the order you pop them.
Invariant: nodes popped in the same BFS layer are in left-to-right order, so you can chain Next pointers linearly.
Algorithm (step-by-step)
- If root is nil, return nil.
- Push root into a queue.
- While queue not empty:
- Let
nbe the level size. - Pop the first node as
prev. - For the remaining
n-1nodes, popcur, setprev.Next = cur, then advanceprev = cur. - Set the last node's
Nextto nil (or leave as nil). - Enqueue children of each popped node as you go.
- Let
- Return root.
Correctness sketch
- Invariant: nodes popped in the same BFS layer are in left-to-right order, so you can chain
Nextpointers linearly. - The queue holds exactly the current level’s nodes before each level pass.
- Processing
sizenodes and enqueueing children builds the next level correctly. - Collected level results therefore match the required traversal.
Trace (hand walkthrough)
Trace Walkthrough
Example input:
1
/ \
2 3
/ \ \
4 5 7
Level links:
1 -> nil
2 -> 3 -> nil
4 -> 5 -> 7 -> nil
Walk:
- level 0: 1.next = nil
- level 1: 2.next = 3, 3.next = nil
- level 2: 4.next = 5, 5.next = 7, 7.next = nil
Pitfalls to avoid
- Using
nextpointers before they are built for the current level. - Forgetting to reset the dummy/tail each level.
Complexity
- Time:
O(n) - Extra space:
O(n)for the queue.
Implementation notes (Go)
- Use a dummy head and tail to build the next level in O(1) extra space.
- Reset dummy/tail each level; advance using existing
Nextpointers.
Run tests to see results
No issues detected