117. Populating Next Right Pointers in Each Node II
Problem
In any binary tree, set each node's next pointer to the node immediately to its right on the same level, or null if it is the rightmost.
Example: [1,2,3,4,5,null,7] → levels linked as 1→null, 2→3→null, 4→5→7→null
Constraints: follow-up: O(1) extra space.
Arbitrary tree. Walk the current level through its next pointers while building the next level's chain with a dummy head + tail pointer. 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: "Node") -> "Node":
level = root
while level:
dummy = tail = Node(0)
node = level
while node:
for child in (node.left, node.right):
if child:
tail.next = tail = child
node = node.next
level = dummy.next
return root
n = {i: Node(i) for i in range(1, 8)}
n[1].left, n[1].right = n[2], n[3]
n[2].left, n[2].right, n[3].right = n[4], n[5], n[7]
Solution().connect(n[1])
assert n[2].next is n[3] and n[4].next is n[5] and n[5].next is n[7] and n[7].next is None
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 level = root; level != null; ) {
Node dummy = new Node(0), tail = dummy;
for (Node n = level; n != null; n = n.next) {
if (n.left != null) tail = tail.next = n.left;
if (n.right != null) tail = tail.next = n.right;
}
level = dummy.next;
}
return root;
}
}
type Node struct { // provided by LeetCode
Val int
Left *Node
Right *Node
Next *Node
}
func connect(root *Node) *Node {
for level := root; level != nil; {
dummy := &Node{} // collects the next level through .Next
tail := dummy
for node := level; node != nil; node = node.Next {
for _, child := range []*Node{node.Left, node.Right} {
if child != nil {
tail.Next = child
tail = child
}
}
}
level = dummy.Next
}
return root
}