04
Next pointers (Tree BFS Sub-pattern)
Link every node to the next node on its level. A level that is already linked is a linked list, so it can drive the linking of the level below.
Signals in the problem statement
- ›
"populate each next pointer to point to its next right node"
- ›
"if there is no next right node, set it to NULL"
- ›
"you may only use constant extra space"
What makes it different
Both are easy with a queue (O(width) space); the follow-up asks for O(1) space. In LC 116 the tree is perfect, so every node has two children: left->next = right, and right->next = next->left across parents. LC 117 allows any shape, so next->left may not exist. Walk the level by next and append each child to the level below with a dummy head and a tail pointer.
Questions
ordered from “learn the idea” to “recognise it without help”- 1Populating Next Right Pointers in Each NodeWalkthroughMediumBasic Anchor·LeetCode #116
- 2Populating Next Right Pointers in Each Node IIWalkthroughMediumMedium·LeetCode #117
Template
next-pointers-template.cpp
// Next pointers in O(1) space: walk the current level through its `next` links
// while building the level below with a dummy head. Works for any shape of tree.
// struct Node { int val; Node *left, *right, *next; }; (given by LeetCode)
Node* connect(Node* root) {
Node* levelStart = root;
while (levelStart) {
Node dummy(0); // dummy.next will be the first node of the level below
Node* tail = &dummy;
for (Node* cur = levelStart; cur; cur = cur->next) { // this level is already linked
if (cur->left) { tail->next = cur->left; tail = tail->next; }
if (cur->right) { tail->next = cur->right; tail = tail->next; }
}
levelStart = dummy.next; // go down one level
}
return root;
}Remember this · Tree BFS
Trigger
Level order, per-level max/average, right side view, minimum depth, nodes at distance k.
Think
Does the question care about depth / rows rather than paths?
Key question
How many nodes are in the current level (queue size at the start of the level)?