Populating Next Right Pointers solution explained

To populate next right pointers in a perfect binary tree with constant extra space, walk the tree one level at a time using the next pointers you already set on the level above. For each node on that level, point its left child to its right child, and point its right child to the left child of the node's next neighbour. This visits every node once, so it runs in O(n) time with O(1) extra space.

By Published 8 min read

The problem, in our words

Each node of the tree has a value, a left child, a right child and an extra pointer called next, which starts out empty. The tree is perfect: every internal node has two children and all leaves sit at the same depth. Fill in next so that it points to the node directly to the right on the same level. The rightmost node of every level keeps next as null. Return the root.

          10
        /    \
       6      15
      / \    /  \
     3   8  12   20

Level 0: 10 -> null
Level 1: 6 -> 15 -> null
Level 2: 3 -> 8 -> 12 -> 20 -> null
A tree drawn for this page, with the links each level should end up with

Notice the link from 8 to 12. Those two nodes have different parents, so no single parent can connect them by looking only at its own children. That cross-parent link is the whole difficulty of the problem.

Why it gets asked

Most candidates solve it with breadth-first search in a few minutes. The interview starts after that, when the interviewer asks for constant extra space. The question then tests whether you can see that the structure you are building is itself useful: once a level is linked, it is a linked list you can walk without a queue. Recursion is usually allowed in the strict version too, with the call stack not counted, but the iterative answer avoids the argument altogether.

  • Any binary tree (the follow-up). Children may be missing and leaves may sit at different depths, so the right child of one node may need to link to a node several parents away.
  • Right side view. The last node of each linked level is the one you see from the right.
  • Print each level using only next pointers. Once the links exist, start at the leftmost node of each level and follow next.

First version: a queue, one level at a time

Breadth-first search already visits nodes level by level. Record how many nodes are in the queue, pop exactly that many, and link each popped node to the one popped after it, except the last on the level. This is correct for any binary tree, not only perfect ones, and it is the natural first answer. The cost is the queue: the bottom level of a perfect tree holds about half of all nodes, so the extra space is O(n).

from collections import deque

class Node:
    def __init__(self, val=0, left=None, right=None, next=None):
        self.val = val
        self.left = left
        self.right = right
        self.next = next

def connect_with_queue(root):
    if root is None:
        return root
    queue = deque([root])
    while queue:
        size = len(queue)
        prev = None
        for _ in range(size):
            node = queue.popleft()
            if prev:
                prev.next = node
            prev = node
            if node.left:
                queue.append(node.left)
            if node.right:
                queue.append(node.right)
    return root
Python: level-by-level queue. O(n) time, O(n) space. Our test reference.

Constant space: use the level above

Suppose level k is already linked. Walk it from its leftmost node using next. Every node on it creates two links in level k + 1. The first is inside the family: node.left.next = node.right. The second crosses to the neighbouring family: if node.next exists, node.right.next = node.next.left. When the walk ends, level k + 1 is fully linked, and its leftmost node is the left child of level k's leftmost node. Start with the root, which is a level of one node and needs no link, and stop when the leftmost node has no children.

On the example: at level 0, node 10 links 6 to 15. At level 1, node 6 links 3 to 8, and because 6.next is 15, it links 8 to 15's left child, 12. Then node 15 links 12 to 20, and 15 has no next, so 20 stays null.

def connect(root):
    leftmost = root
    while leftmost and leftmost.left:
        node = leftmost
        while node:
            node.left.next = node.right
            if node.next:
                node.right.next = node.next.left
            node = node.next
        leftmost = leftmost.left
    return root
Python: walk each linked level to wire the next. O(n) time, O(1) extra space.
function connect(root) {
  let leftmost = root;
  while (leftmost !== null && leftmost.left !== null) {
    let node = leftmost;
    while (node !== null) {
      node.left.next = node.right;
      if (node.next !== null) {
        node.right.next = node.next.left;
      }
      node = node.next;
    }
    leftmost = leftmost.left;
  }
  return root;
}
JavaScript: the same two links per node, no queue.

The code relies on the tree being perfect in two places: every node on a non-bottom level has both children, and the leftmost node's left child is always the start of the next level. Say both assumptions aloud, because they are exactly what breaks in the follow-up.

Follow-up: any binary tree

When children can be missing, a node's right neighbour might be the child of a parent far to the right, and the next level might not start under the leftmost node. Keep the idea of walking the linked level above, but build the level below like a linked list with a dummy head. For each parent, append whichever children exist to the tail. When the parent level is done, the dummy's next is the first node of the new level, or null if there were no children at all.

def connect_any_tree(root):
    head = root
    while head:
        dummy = Node(0)
        tail = dummy
        parent = head
        while parent:
            for child in (parent.left, parent.right):
                if child:
                    tail.next = child
                    tail = child
            parent = parent.next
        head = dummy.next
    return root
Python: general tree, dummy head per level. O(n) time, O(1) extra space.

Complexity

n nodes
ApproachTimeExtra spaceTree shape
Queue, level by levelO(n)O(n) (widest level)Any
Recursive: link children, then recurseO(n)O(log n) call stackPerfect
Walk the linked level aboveO(n)O(1)Perfect
Dummy head per child levelO(n)O(1)Any
n nodes. Scroll sideways on a small screen.

Edge cases

  • An empty tree: return null without touching anything.
  • A single node: its next stays null, and the outer loop never runs because it has no left child.
  • Two levels: only one link is made, from the root's left child to its right child, with no cross-family link.
  • The rightmost node of every level must end with next set to null. With fresh nodes that is automatic, but if the tree arrives with stale next values, clear them.
  • For the follow-up: a level with a gap in the middle, a parent with only a right child, and a tree that is a one-sided chain.

Mistakes that cost points

  • Linking only within a family, which leaves the 8 to 12 style links missing.
  • Moving down with leftmost = leftmost.next instead of leftmost.left, which never leaves the current level.
  • Running the perfect-tree code on a general tree, where node.left can be null and the code crashes.
  • Calling the recursive version O(1) space without mentioning the call stack.
  • In the dummy-head version, reusing one dummy across levels without resetting its next, so an empty level is never detected and the loop repeats.

How to explain it out loud

Fictional example

Moving from the queue to constant space
Candidate
A level-order queue works, but the last level holds half the nodes, so that is linear space.
Candidate
Once a level is linked it behaves like a linked list. I can walk it and, for each node, link its left child to its right child, and its right child to the next node's left child.
Candidate
Then I drop to the leftmost node's left child and repeat. Every node is touched once, and I keep only two pointers.
Interviewer
And if the tree is not perfect?
Candidate
I build each lower level with a dummy head and a tail, appending whichever children exist. Still one pass and constant space.

Binary Tree Level Order Traversal is the queue technique used in the first version. Vertical Order Traversal groups nodes by column instead of by level. Convert Sorted Array to BST builds a balanced tree of the kind this problem walks, and Sum Root to Leaf Numbers is a depth-first contrast.

Where Natively fits

This is a problem where the second answer matters more than the first. In practice on Mac or Windows, Natively can read the prompt from a screenshot, and when you are stuck on the constant-space step you can ask it for a hint about using the links you have already made. The transcript of your mock round shows whether you named the perfect-tree assumptions out loud. Read more about the AI interview assistant.

Questions people ask

How do you populate next right pointers in a perfect binary tree?

Walk each level through the next pointers already set above it. For every node, link its left child to its right child, and its right child to the left child of the node's next neighbour.

Can you populate next right pointers in O(1) space?

Yes. A finished level is a linked list, so you can walk it without a queue to connect the level below. Only a couple of pointers are needed.

What is the time complexity of Populating Next Right Pointers?

O(n), since each node is visited once. The queue version also takes O(n) time but needs O(n) extra space for the widest level.

What changes if the tree is not perfect?

Children can be missing, so build each lower level with a dummy head and a tail pointer, appending whichever children exist. It stays O(n) time and O(1) space.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP