Populate next right pointers in each node
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Meta's technical phone screen, last asked Feb 2026. It tests trees, linked lists and bfs.
You get the root of a binary tree. Each node has val, left, right and a next pointer that starts as null. Set every node's next to the node immediately to its right on the same level, or null if it is the last node of its level. The tree is not necessarily perfect or complete. Do it in O(n) time and O(1) extra space: no BFS queue.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
connect(root: Node | None) -> Node | None— fills in thenextpointers in place and returnsroot.
Example
1
/ \
2 3
/ \ \
4 5 7
after connect:
1 -> null
2 -> 3 -> null
4 -> 5 -> 7 -> null
Reading each level through next pointers, with # marking the end of a level, gives [1, #, 2, 3, #, 4, 5, 7, #]. An empty tree gives []; a single node gives [1, #].
Constraints
-
0 <= number of nodes <= 10^5. -
-10^9 <= val <= 10^9. - Gaps can appear anywhere in a level.
Clarifying questions
- Is the tree perfect, or can any child be missing?
- Does recursion stack count as extra space?
- Should I return the root, or only modify in place?
What a strong answer covers
- The easy version first: BFS with a queue, linking nodes level by level,
O(n)time andO(width)space. - The constant-space idea: once a level is linked, walk it through
nextpointers and build the level below as a linked list, using a dummy head and a tail pointer. - Why the perfect-tree shortcut (
node.left.next = node.right,node.right.next = node.next.left) fails when children are missing. -
O(n)time,O(1)extra space. - Tests: empty tree, one node, a skewed tree, gaps in the middle of a level, a perfect tree.
Follow-ups
- Solve the perfect binary tree version with the simplest code you can.
- Link each level from right to left instead.
- Return the rightmost node of every level using the
nextpointers you built.
Where it's asked
- Meta · Technical phone screen · Last asked Feb 202645 min · Two coding problems in CoderPad, about 20 minutes each · Usually no AI; some newer screens are AI-assisted
What it tests
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
