Losing head/tail while rewiring
Wrong move: Pointer updates overwrite references before they are saved.
Usually fails on: List becomes disconnected mid-operation.
Fix: Store next pointers first and use a dummy head for safer joins.
Move from brute-force thinking to an efficient approach using linked list strategy.
You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition:
struct Node {
int val;
Node *left;
Node *right;
Node *next;
}
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.
Initially, all next pointers are set to NULL.
Example 1:
Input: root = [1,2,3,4,5,6,7] Output: [1,#,2,3,#,4,5,6,7,#] Explanation: Given the above perfect binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level.
Example 2:
Input: root = [] Output: []
Constraints:
[0, 212 - 1].-1000 <= Node.val <= 1000Follow-up:
Problem summary: You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition: struct Node { int val; Node *left; Node *right; Node *next; } Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL. Initially, all next pointers are set to NULL.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Linked List · Tree
[1,2,3,4,5,6,7]
[]
populating-next-right-pointers-in-each-node-ii)binary-tree-right-side-view)cycle-length-queries-in-a-tree)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #116: Populating Next Right Pointers in Each Node
/*
// Definition for a Node.
class Node {
public int val;
public Node left;
public Node right;
public Node next;
public Node() {}
public Node(int _val) {
val = _val;
}
public Node(int _val, Node _left, Node _right, Node _next) {
val = _val;
left = _left;
right = _right;
next = _next;
}
};
*/
class Solution {
public Node connect(Node root) {
if (root == null) {
return root;
}
Deque<Node> q = new ArrayDeque<>();
q.offer(root);
while (!q.isEmpty()) {
Node p = null;
for (int n = q.size(); n > 0; --n) {
Node node = q.poll();
if (p != null) {
p.next = node;
}
p = node;
if (node.left != null) {
q.offer(node.left);
}
if (node.right != null) {
q.offer(node.right);
}
}
}
return root;
}
}
// Accepted solution for LeetCode #116: Populating Next Right Pointers in Each Node
/**
* Definition for a Node.
* type Node struct {
* Val int
* Left *Node
* Right *Node
* Next *Node
* }
*/
func connect(root *Node) *Node {
if root == nil {
return root
}
q := []*Node{root}
for len(q) > 0 {
var p *Node
for n := len(q); n > 0; n-- {
node := q[0]
q = q[1:]
if p != nil {
p.Next = node
}
p = node
if node.Left != nil {
q = append(q, node.Left)
}
if node.Right != nil {
q = append(q, node.Right)
}
}
}
return root
}
# Accepted solution for LeetCode #116: Populating Next Right Pointers in Each Node
"""
# Definition for a Node.
class Node:
def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
self.val = val
self.left = left
self.right = right
self.next = next
"""
class Solution:
def connect(self, root: "Optional[Node]") -> "Optional[Node]":
if root is None:
return root
q = deque([root])
while q:
p = None
for _ in range(len(q)):
node = q.popleft()
if p:
p.next = node
p = node
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
return root
// Accepted solution for LeetCode #116: Populating Next Right Pointers in Each Node
// Rust example auto-generated from java reference.
// Replace the signature and local types with the exact LeetCode harness for this problem.
impl Solution {
pub fn rust_example() {
// Port the logic from the reference block below.
}
}
// Reference (java):
// // Accepted solution for LeetCode #116: Populating Next Right Pointers in Each Node
// /*
// // Definition for a Node.
// class Node {
// public int val;
// public Node left;
// public Node right;
// public Node next;
//
// public Node() {}
//
// public Node(int _val) {
// val = _val;
// }
//
// public Node(int _val, Node _left, Node _right, Node _next) {
// val = _val;
// left = _left;
// right = _right;
// next = _next;
// }
// };
// */
//
// class Solution {
// public Node connect(Node root) {
// if (root == null) {
// return root;
// }
// Deque<Node> q = new ArrayDeque<>();
// q.offer(root);
// while (!q.isEmpty()) {
// Node p = null;
// for (int n = q.size(); n > 0; --n) {
// Node node = q.poll();
// if (p != null) {
// p.next = node;
// }
// p = node;
// if (node.left != null) {
// q.offer(node.left);
// }
// if (node.right != null) {
// q.offer(node.right);
// }
// }
// }
// return root;
// }
// }
// Accepted solution for LeetCode #116: Populating Next Right Pointers in Each Node
/**
* Definition for Node.
* class Node {
* val: number
* left: Node | null
* right: Node | null
* next: Node | null
* constructor(val?: number, left?: Node, right?: Node, next?: Node) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* this.next = (next===undefined ? null : next)
* }
* }
*/
function connect(root: Node | null): Node | null {
if (root == null || root.left == null) {
return root;
}
const { left, right, next } = root;
left.next = right;
if (next != null) {
right.next = next.left;
}
connect(left);
connect(right);
return root;
}
Use this to step through a reusable interview workflow for this problem.
Copy all n nodes into an array (O(n) time and space), then use array indexing for random access. Operations like reversal or middle-finding become trivial with indices, but the O(n) extra space defeats the purpose of using a linked list.
Most linked list operations traverse the list once (O(n)) and re-wire pointers in-place (O(1) extra space). The brute force often copies nodes to an array to enable random access, costing O(n) space. In-place pointer manipulation eliminates that.
Review these before coding to avoid predictable interview regressions.
Wrong move: Pointer updates overwrite references before they are saved.
Usually fails on: List becomes disconnected mid-operation.
Fix: Store next pointers first and use a dummy head for safer joins.
Wrong move: Recursive traversal assumes children always exist.
Usually fails on: Leaf nodes throw errors or create wrong depth/path values.
Fix: Handle null/base cases before recursive transitions.