Connect Level Neighbors
MediumThis is an extra practice problem. It doesn't have walkthrough slides. You can solve it with the pattern template you already know. Open the hints if you get stuck.
Question
Given the root of a binary tree, give every node a next pointer to the node immediately to its right on the same level. If a node is the last one on its level, its next pointer should be None.
The tree isn't guaranteed to be perfect. Some nodes may have only one child, or no children at all, at any level.
Return the root once every node's next pointer is set.
Input: root = [21, 14, 28, 7, 17, None, 35]
Output: [21 -> None], [14 -> 28 -> None], [7 -> 17 -> 35 -> None]
14 links to its sibling 28. Notice that 17 links to 35 even though they don't share a parent.
Input: root = [40, 25, None]
Output: [40 -> None], [25 -> None]
Each level only has one node, so every next pointer is None.
Input: root = [9, None, 12, None, None, None, 20]
Output: [9 -> None], [12 -> None], [20 -> None]
You might also hear this problem called “Populating Next Right Pointers in Each Node.”
Clarify the problem
What are some questions you'd ask an interviewer?
Understand the problem
Remember to understand the problem and plan your approach before you start coding.