116. Populating Next Right Pointers in Each Node
Problem
In a perfect binary tree (every level full), set each node's next pointer to the node immediately to its right on the same level, or null for the rightmost node.
Example: [1,2,3,4,5,6,7] → levels linked as 1→null, 2→3→null, 4→5→6→7→null
Constraints: follow-up: O(1) extra space (recursion stack doesn't count).
Perfect tree → use the already-built next pointers of level i to wire level i+1: left.next = right, right.next = node.next.left. O(1) extra space.
Complexity: O(n) time, O(1) space.
class Node: # provided by LeetCode
def __init__(self, val=0, left=None, right=None, next=None):
self.val, self.left, self.right, self.next = val, left, right, next
class Solution:
def connect(self, root: "Optional[Node]") -> "Optional[Node]":
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
n = [Node(i) for i in range(8)] # 1..7 used, heap layout
for i in range(1, 4):
n[i].left, n[i].right = n[2 * i], n[2 * i + 1]
Solution().connect(n[1])
assert n[4].next is n[5] and n[5].next is n[6] and n[6].next is n[7] and n[7].next is None and n[2].next is n[3]
assert Solution().connect(None) is None
class Node { // provided by LeetCode
int val; Node left, right, next;
Node(int val) { this.val = val; }
}
class Solution {
public Node connect(Node root) {
for (Node leftmost = root; leftmost != null && leftmost.left != null; leftmost = leftmost.left)
for (Node n = leftmost; n != null; n = n.next) {
n.left.next = n.right;
if (n.next != null) n.right.next = n.next.left;
}
return root;
}
}
type Node struct { // provided by LeetCode
Val int
Left *Node
Right *Node
Next *Node
}
func connect(root *Node) *Node {
for leftmost := root; leftmost != nil && leftmost.Left != nil; leftmost = leftmost.Left {
for node := leftmost; node != nil; node = node.Next { // walk this level with the links built so far
node.Left.Next = node.Right
if node.Next != nil {
node.Right.Next = node.Next.Left
}
}
}
return root
}