← Questions

Populate next pointers in a perfect binary tree

0
MicrosoftCodingLast asked Feb 2026

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:

  • Node has val, left, right, next (initially None).
  • connect(root: Node | None) -> Node | None — fills in next pointers 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 next pointers already set on it, and for each node set left.next = right and right.next = node.next.left when node.next exists; then move down to the leftmost node of the next level.
  • Why the perfect-tree guarantee makes node.next.left always 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 next pointers 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

trees · bfs · pointers

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding