Populating Next Right Pointers in Each Node

Link every node of a perfect binary tree to the node on its right, one level at a time, without a queue.

Given a perfect binary tree, one where every node has either two children or none and all the childless nodes sit on the bottom level, fill in one extra pointer in each node. Besides its value and its two children, each node has a pointer named next, which starts as null. Set every next to the node directly to its right on the same level, and leave it null for the last node of a level. Try to use only a fixed amount of extra memory, however big the tree is.

The examples write the tree's values level by level, from the top. The output follows the next pointers across each level and puts a # where a level ends.

Example 1
Input: root = [1, 2, 3, 4, 5, 6, 7]
Output: [1, #, 2, 3, #, 4, 5, 6, 7, #]
Example 2
Input: root = []
Output: []
Solution

The Idea

Think of a family tree drawn on paper, one generation per row. Linking each person to the next person on the same row, even a cousin with different parents, is exactly what this problem asks for the tree's nodes.

Look at Example 1. The root, 1, sits alone on the top level. Its children, 2 and 3, form the second level. Node 2 has the children 4 and 5, and node 3 has 6 and 7. After the work is done, 2 points to 3, and the bottom level reads 4, 5, 6, 7. The link from 5 to 6 is the interesting one, because 5 and 6 have different parents.

The plain way to visit a tree level by level keeps a waiting line of nodes, called a queue, and that line can hold a whole level at once. The bottom level of a perfect tree holds about half of all its nodes. So can the links be made without such a line?

They can, because each finished level is already a line of its own. Once 2 points to 3, the second level can be read from left to right by starting at 2 and following next from node to node, like a chain. And while reading it, each node can reach its own children and, through next, its neighbour's children. Look at the picture below.

The tree 1 to 7. The level 2, 3 is already linked by next and is walked from 2 to 3. While walking it, the level below gets its links: 4 to 5 and 6 to 7 join children of the same parent, and 5 to 6 crosses to the neighbour 3's left child. 3 and 7 point to null.

The green band, labelled "the level being walked", holds 2 then 3. At node 2, the blue arrow 4 → 5 joins two children of the same parent, 2. The orange arrow 5 → 6 goes from 2's right child to the left child of 2's neighbour, 3. At node 3, the arrow 6 → 7 joins 3's own children. Node 3 has no neighbour, so 7 keeps null, just as 3 does.

Now the bottom level is linked too, and it can be walked in the same way to link a level below it, if there is one. The top level needs no work at all: the root is alone, so its next stays null. So each level is linked while walking the level above it, using links made in the round before.

Solution Approach

Turning this level-by-level linking into code means looking at the plain way with a queue and its memory cost, then settling which two links each node makes and how to move down a level.

The plain way with a queue

How would a level-by-level visit link the nodes? Start with the root in the queue. Each round takes out all the nodes of one level, links each one to the node taken out after it, and puts their children at the back of the queue. That works, but the queue holds up to a whole level. For a tree of n nodes, the bottom level alone holds about n/2, so the queue's memory grows with the tree and misses the goal of a fixed amount.

The two links each node makes

Which links can one node of the walked level set? First, its left child's next becomes its right child, like 4 → 5 under node 2. In a perfect tree, a node with children always has both, so this link is always there to make.

Second, its right child's next becomes the left child of the node's own neighbour, like 5 → 6, where the neighbour of 2 is 3. When the node is last on its level, as 3 is, there is no neighbour, and the right child keeps the null it started with.

Moving down a level

Where does the next walk start, and when does it stop? Each level starts at its leftmost node, and the leftmost node of the level below is the left child of the current one: 1, then 2, then 4. The walk goes on while that leftmost node has a left child. In a perfect tree, if the first node of a level has no children, no node on that level has any, so there is nothing left to link.

Java Solution

The method connect works in these steps:

  1. First, set leftmost to root. This pointer always marks the first node of the level being walked.
  2. An outer while loop runs as long as leftmost is not null and has a left child, which means a level below exists. For an empty tree or a lone root it never runs.
  3. Inside, a for loop walks the level: node starts at leftmost and moves on with node = node.next until it reaches null.
  4. For each node, set node.left.next = node.right. If node.next is not null, also set node.right.next = node.next.left.
  5. After the walk, move leftmost down to leftmost.left. When the outer loop ends, return root.

Three small helpers surround the method. Node is the tree node, with val, left, right and next. The helper build makes a perfect tree from its values level by level, as in the examples. The helper levels prints the tree in the output form, and it moves across a level only by following next, so it shows exactly which links were made.

The main method prints the Example 1 tree once before connect and once after, then runs an empty tree, a lone root and a tree with four levels.

Java
import java.util.ArrayList;
import java.util.List;

public class PopulatingNextRightPointers {

    static class Node {
        int val;
        Node left, right, next;
        Node(int val) { this.val = val; }
    }

    public static Node connect(Node root) {
        Node leftmost = root;
        while (leftmost != null && leftmost.left != null) {      // a level below exists
            for (Node node = leftmost; node != null; node = node.next) { // walk this level
                node.left.next = node.right;                     // children of the same parent
                if (node.next != null) {
                    node.right.next = node.next.left;            // across to the neighbour's child
                }
            }
            leftmost = leftmost.left;                            // go down one level
        }
        return root;
    }

    // Builds a perfect tree from its values in level order: the children of
    // the node at index i sit at indexes 2i + 1 and 2i + 2.
    static Node build(int... values) {
        Node[] nodes = new Node[values.length];
        for (int i = values.length - 1; i >= 0; i--) {
            nodes[i] = new Node(values[i]);
            if (2 * i + 2 < values.length) {
                nodes[i].left = nodes[2 * i + 1];
                nodes[i].right = nodes[2 * i + 2];
            }
        }
        return values.length == 0 ? null : nodes[0];
    }

    // Reads each level by following next pointers only, with # after each level.
    static String levels(Node root) {
        List<String> out = new ArrayList<>();
        for (Node first = root; first != null; first = first.left) {
            for (Node node = first; node != null; node = node.next) {
                out.add(String.valueOf(node.val));
            }
            out.add("#");
        }
        return out.toString();
    }

    public static void main(String[] args) {
        System.out.println(levels(build(1, 2, 3, 4, 5, 6, 7)));          // before connect
        System.out.println(levels(connect(build(1, 2, 3, 4, 5, 6, 7))));
        System.out.println(levels(connect(build())));
        System.out.println(levels(connect(build(1))));
        int[] fourLevels = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
        System.out.println(levels(connect(build(fourLevels))));
    }
}

Running it prints:

Output
[1, #, 2, #, 4, #]
[1, #, 2, 3, #, 4, 5, 6, 7, #]
[]
[1, #]
[1, #, 2, 3, #, 4, 5, 6, 7, #, 8, 9, 10, 11, 12, 13, 14, 15, #]

Look at the first line, [1, #, 2, #, 4, #]. Before connect, every next is null, so levels finds only the first node of each level: 1, 2 and 4. The second line is the same tree after connect, and its bottom level reads 4, 5, 6, 7, so the link from 5 across to 6 was made.

The empty tree prints [] and the lone root prints [1, #]: in both, the outer loop never ran. On the last line, the fourth level reads 8 to 15. That level was linked while walking 4, 5, 6, 7, using the links made in the round before.

The link across to the neighbour's child is easy to leave out, since joining each node's two children can look like enough. A copy of the program without the if block prints [1, #, 2, 3, #, 4, 5, #] for Example 1. Node 5's next stays null, so following next along the bottom level stops after 5, and 6 and 7 are never reached.

Complexity

The method visits each node with children once and keeps nothing but two pointers.

  • Time: O(n), because the for loop visits each node above the bottom level once, fewer than n visits in all, and each visit sets at most two pointers.
  • Space: O(1), a fixed amount, because the method keeps only leftmost and node, with no queue and no recursion, since the next links of the level above give the order to visit.

The version with a queue is the plain level order traversal.