Populate next pointers in a perfect binary tree
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Microsoft's coding round, last asked Feb 2026. It tests trees, bfs and pointers.
You are given a perfect binary tree: every internal node has two children and all leaves are on the same level. Each node has left, right and next. Set every node's next to the node immediately to its right on the same level, or None for the last node of a level, using O(1) extra space.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
Nodehasval,left,right,next(initiallyNone). -
connect(root: Node | None) -> Node | None— fills innextpointers and returns the root.
Trees below are written in level order; the output lists each node's next value in the same order.
Example
[1, 2, 3, 4, 5, 6, 7] -> [None, 3, None, 5, 6, 7, None]
# 2 -> 3; 4 -> 5 -> 6 -> 7
[1] -> [None]
[] -> []
Constraints
- Up to 2^12 - 1 nodes.
- O(1) extra space; a recursion stack is allowed only if the interviewer agrees.
Clarifying questions
- Is the tree guaranteed perfect?
- Does recursion count as extra space?
- Can the root be
None?
What a strong answer covers
- The BFS with a queue as the easy O(n)-space version.
- The O(1) version: walk each level through the
nextpointers already set on it, and for each node setleft.next = rightandright.next = node.next.leftwhennode.nextexists; then move down to the leftmost node of the next level. - Why the perfect-tree guarantee makes
node.next.leftalways available. - O(n) time, O(1) space.
- Tests: empty tree, single node, three levels.
Follow-ups
- The tree is any binary tree, not perfect: still O(1) space (use a dummy head per level).
- Return the levels as lists using only
nextpointers after connecting. - Connect each level into a circle instead.
Where it's asked
- Microsoft · Coding · Last asked Feb 202660 min · Ten to fifteen minutes of behavioral questions, then coding in HackerRank where you write a main and make the tests pass; usually three rounds · No AI unless the interviewer invites it; some 2026 loops add a round where you bring your own AI agent
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.
