Populating Next Right Pointers in Each Node II
MediumTop Interview 150 TreesProblem
Every node of a binary tree has a left child, a right child, and an extra
next pointer that starts out as null. The tree is not necessarily full: nodes may have
one child, two, or none.
Fill in every next pointer so that it points to the node immediately to the right on the same
level, or stays null for the last node of a level. Return the root.
The tree is given in level order with null for a missing child. The answer lists each level, read by
following the next pointers from its first node.
Constraints
- 0 ≤ number of nodes ≤ 6000
- -100 ≤ Node.val ≤ 100
- Use only constant extra space (the recursion stack does not count)
Examples: pick one to animate
Solutions
Time: Every node is visited once while its row is scanned, and each child is linked once.
Space: Only a few pointers (level, cur, tail and the dummy) are used. The next pointers that are being built double as the queue.
Once a row is linked, its next pointers let us walk it without a queue. While walking row k, link its
children into row k+1 with a tail pointer that starts at a dummy node. The dummy's next is the
first node of row k+1, so the walk can drop straight down to it, whichever parent that child had.