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 nextnullnextnull
The examples write the tree's values level by level, from the top. The output follows the next#
Example 1
Output: [1, #, 2, 3, #, 4, 5, 6, 7, #]
Example 2
Output: []
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 nextnext
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
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 nextnull
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
Second, its right child's nextnull
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
- First, set
toleftmost . This pointer always marks the first node of the level being walked.root - An outer
loop runs as long aswhile is notleftmost and has a left child, which means a level below exists. For an empty tree or a lone root it never runs.null - Inside, a
loop walks the level:for starts atnode and moves on withleftmost until it reachesnode = node.next .null - For each
, setnode . Ifnode.left.next = node.right is notnode.next , also setnull .node.right.next = node.next.left - After the walk, move
down toleftmost . When the outer loop ends, returnleftmost.left .root
Three small helpers surround the method. Nodevalleftrightnextbuildlevelsnext
The mainconnect
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:
[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, #]connectnextnulllevelsconnect
The empty tree prints [][1, #]
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[1, #, 2, 3, #, 4, 5, #]nextnullnext
Complexity
The method visits each node with children once and keeps nothing but two pointers.
- Time: O(n), because the
loop visits each node above the bottom level once, fewer than n visits in all, and each visit sets at most two pointers.for - Space: O(1), a fixed amount, because the method keeps only
andleftmost , with no queue and no recursion, since thenode links of the level above give the order to visit.next
The version with a queue is the plain