Populating Next Right Pointers In Each Node II Problem
Description
LeetCode Problem 117.
Given a binary tree
struct Node {
int val;
Node *left;
Node *right;
Node *next;
}
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.
Initially, all next pointers are set to NULL.
Example 1:
Input: root = [1,2,3,4,5,null,7]
Output: [1,#,2,3,#,4,5,7,#]
Explanation: Given the above binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level.
Example 2:
Input: root = []
Output: []
Constraints:
- The number of nodes in the tree is in the range [0, 6000].
- -100 <= Node.val <= 100
Solution
Approach: Link the Next Level While Walking the Current One (O(1) Space)
A breadth-first search with a queue would work, but needs O(n) extra space. We can avoid the queue: once a level is linked through next, it can be walked from left to right like a linked list, and while doing so we can chain its children into the next level.
Unlike in a perfect tree, children can be missing anywhere, so the neighbour of a child may sit under a parent several positions to the right. Rather than searching for it, build the level below as a linked list as we meet its nodes:
- Start with
levelStart = root(a single node is already a linked level). - For each level, create a
dummynode and settail = dummy.tailis the last node linked so far on the level below. - Walk the current level with
node = levelStart, followingnext. For each existing child ofnode, left first, settail.next = childand movetailto it. - When the level is done,
dummy.nextis the first node of the level below. Continue withlevelStart = dummy.next. When the last level has no children, it isnulland the loop ends.
The dummy node saves a special case. Without it, the first child found on each level would need separate code to remember where the level starts. With it, every child is appended the same way.
For [1,2,3,4,5,null,7]: walking 2 -> 3 appends 4, 5, then 7, giving 4 -> 5 -> 7, even though 5 and 7 have different parents and 3 has no left child.
The last node appended on each level is never given a next, so it keeps null, as required.
Complexity: O(n) time, where n is the number of nodes, and O(1) extra space: only a dummy node and a few pointers.
class Solution:
def connect(self, root: 'Node') -> 'Node':
level_start = root # first node of a level whose next pointers are already set
while level_start is not None:
dummy = Node(0) # placeholder in front of the level below
tail = dummy # last node linked so far on the level below
# Walk the current level through its next pointers and chain up its children.
node = level_start
while node is not None:
if node.left is not None:
tail.next = node.left
tail = tail.next
if node.right is not None:
tail.next = node.right
tail = tail.next
node = node.next
level_start = dummy.next # the first child found, or None after the last level
return root
Now write it from memory
Close the write-up and solve it yourself against the tests.