Input: root = [1,2,3,4,5,null,7]
Output: [1,#,2,3,#,4,5,7,#]
Explanation: Given the above 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.
The recursive solution is built around the idea that:
The next pointer of a node can be established using its immediate children and the parent’s next pointer.
If a node has:
A left child, its next pointer should point to the right child of the same node (if exists).
A right child or left child (when right is not available) can use the parent’s next pointer to find the next available sibling or cousin at the same level.
The recursion is performed in a top-down manner, ensuring that the children of the current node are connected before moving deeper down the tree.
The recursive approach works in the following steps:
Base Case: If the node is None, return immediately.
Recursive Case:
Connect the left child’s next pointer to the right child (if it exists).
Use a helper function (findNext) to “scan” the parent’s next pointer until it finds the first non-None sibling with children for connecting the current node’s children.
Recurse first on the right subtree and then on the left subtree:
Right subtree is updated first because a node’s next pointer (used in findNext) must already be set when connecting the left subtree.
publicclassSolution {
public Node connect(Node root) {
if (root ==null) returnnull;
// Connect left childif (root.left!=null) {
root.left.next= (root.right!=null) ? root.right : findNext(root);
}
// Connect right childif (root.right!=null) {
root.right.next= findNext(root);
}
// Recursive calls, right first to ensure child "next" pointers are set connect(root.right);
connect(root.left);
return root;
}
private Node findNext(Node root) {
while (root.next!=null) { // Traverse parent level using next pointers root = root.next; // Move to the next parent nodeif (root.left!=null) return root.left; // First left child foundif (root.right!=null) return root.right; // First right child found }
returnnull; // No valid child found }
}
classNode:
def __init__(self, val=0, left=None, right=None, next=None):
self.val = val
self.left = left
self.right = right
self.next = next
classSolution:
defconnect(self, root: Node) -> Node:
ifnot root:
returnNone# Base case: If root is None, return# Connect left child's next pointerif root.left:
if root.right: # Connect to right child if exists root.left.next = root.right
else: # Otherwise, use findNext root.left.next = self.findNext(root)
# Connect right child's next pointerif root.right:
root.right.next = self.findNext(root)
# Recursively connect peers: right subtree first, then left subtree self.connect(root.right)
self.connect(root.left)
return root
deffindNext(self, root: Node) -> Node:
# Find the next node with children on the same levelwhile root.next:
root = root.next
if root.left: # Return the left child if existsreturn root.left
if root.right: # Return the right child if existsreturn root.right
returnNone# No valid next node found
publicclassSolution {
staticclassNode {
int val;
Node left, right, next;
Node(int x) {
val = x;
left = right = next =null;
}
}
public Node connect(Node root) {
if (root ==null) returnnull;
// Queue for level-order traversal Queue<Node> queue =new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
int size = queue.size(); // Number of nodes at the current level Node prev =null;
for (int i = 0; i < size; i++) {
Node node = queue.poll();
// Connect current node's next pointer to the previous nodeif (prev !=null) {
prev.next= node;
}
prev = node;
// Add children to the queueif (node.left!=null) queue.add(node.left);
if (node.right!=null) queue.add(node.right);
}
// Last node in the level points to null prev.next=null;
}
return root;
}
}
classSolution:
defconnect(self, root: Node) -> Node:
ifnot root:
returnNone# Queue for level-order traversal queue = deque([root])
while queue:
size = len(queue) # Number of nodes at the current level prev =Nonefor _ in range(size):
node = queue.popleft()
# Connect current node's next pointer to the previous nodeif prev:
prev.next = node
prev = node
# Add children to the queueif node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
# Last node in the level points to None prev.next =Nonereturn root