Populating Next Right Pointers in Each Node II (LeetCode 117): Solution and Explanation
Given any binary tree whose nodes have a next field, point every node's next at the node to its right on the same level, or null for the last node. Unlike part I, children may be missing anywhere, so a neighbor can be a distant cousin.
Intuition
A level-order BFS with a queue solves it directly: link each node to the one dequeued after it on the same level. That costs O(width) memory, and the follow-up asks for constant space.
Once a level is linked, it is a linked list. Walking it with next visits every parent on that level from left to right, which is exactly the order their children appear on the level below.
So while walking level L, build level L+1 like appending to a linked list: keep a tail pointer prev, set prev.next = child for each child met, and remember the first child as the start of the next walk.
Approach: Walk by next, thread with a tail pointer
- Set
level_start = root. - For each level, set
cur = level_start,prev = Noneand clearlevel_start. - For each non-null child of
cur(left, then right): ifprevexists setprev.next = child, otherwise recordlevel_start = child. Thenprev = child. - Move
cur = cur.nextuntil the level ends, then repeat from the recordedlevel_start. Stop when no child was found.
Step-by-step example
root = [1,2,3,4,5,null,7]
- Level 0 is just node 1. Its children 2 and 3 are threaded: level_start = 2, then 2.next = 3.
- Walk level 1 from 2. Node 2's children: 4 becomes level_start, then 4.next = 5, prev = 5.
- cur = 2.next = 3. Node 3 has no left child, so skip it. Its right child 7: 5.next = 7, jumping the gap.
- 3.next is null, so level 1 is done. Walk level 2 from 4: no node has children, so level_start stays null and the loop ends.
- Reading next pointers level by level gives [1,#,2,3,#,4,5,7,#].
Code: Python, Java, C++
1class Solution:
2 def connect(self, root: 'Optional[Node]') -> 'Optional[Node]':
3 level_start = root
4 while level_start:
5 cur = level_start
6 prev = None
7 level_start = None
8 while cur:
9 for child in (cur.left, cur.right):
10 if not child:
11 continue
12 if prev:
13 prev.next = child
14 else:
15 level_start = child
16 prev = child
17 cur = cur.next
18 return root1class Solution {
2 public Node connect(Node root) {
3 Node levelStart = root;
4 while (levelStart != null) {
5 Node cur = levelStart;
6 Node prev = null;
7 levelStart = null;
8 while (cur != null) {
9 for (Node child : new Node[]{cur.left, cur.right}) {
10 if (child == null) continue;
11 if (prev != null) {
12 prev.next = child;
13 } else {
14 levelStart = child;
15 }
16 prev = child;
17 }
18 cur = cur.next;
19 }
20 }
21 return root;
22 }
23}1class Solution {
2public:
3 Node* connect(Node* root) {
4 Node* levelStart = root;
5 while (levelStart) {
6 Node* cur = levelStart;
7 Node* prev = nullptr;
8 levelStart = nullptr;
9 while (cur) {
10 for (Node* child : {cur->left, cur->right}) {
11 if (!child) continue;
12 if (prev) {
13 prev->next = child;
14 } else {
15 levelStart = child;
16 }
17 prev = child;
18 }
19 cur = cur->next;
20 }
21 }
22 return root;
23 }
24};Time and space complexity
O(n)
Every node is visited once as a parent (cur) and once as a child.
O(1)
Only the pointers level_start, cur and prev are kept; the next pointers being built replace the queue.
Other approaches
BFS with a queue (time O(n), space O(width))
Process the tree level by level with a queue, linking each node to the next node popped from the same level. Simple, but the queue can hold a whole level.
Dummy head per level (time O(n), space O(1))
The same walk, but the level below starts at a dummy node so the first append needs no special case: tail = dummy, tail.next = child. After the walk, the next level starts at dummy.next.
Recursion right to left (time O(n^2) worst case, space O(h))
Connect a node's children first, finding the right child's neighbor by scanning the parent's next chain for the first child, then recurse into the right subtree before the left. Easy to get wrong if the left subtree is processed first.
Common mistakes
- Reusing the part I trick
node.right.next = node.next.left. In a non-perfect tree the next parent may have no left child, or no children at all. - Forgetting to reset prev to null at the start of each level, which links the last node of one level to the first node of the next.
- Moving down via
level_start.left. If the first node of a level has no children, the next level starts somewhere else; record the first child met instead. - Recursing into the left subtree before the right one, so next pointers needed to find cousins are not set yet.
Frequently asked questions
How is this different from part I?
Part I guarantees a perfect binary tree, so a node's neighbor is always its sibling or its parent's next node's left child. Here children can be missing anywhere, so the neighbor must be found by scanning along the parent level.
Why does walking by next give children in the right order?
The parent level is linked left to right, and each parent's children sit left to right under it, so visiting parents in order and taking left before right lists the child level from left to right.
What does '#' mean in the output?
The output reads each level through next pointers and writes '#' when it reaches a null next, marking the end of that level.