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 <= 1000
Follow-up:
When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
The brute force approach to connecting nodes on the same level is like manually checking every possible pair of nodes. We look at each node and then search through all other nodes on its level to find the one directly to its right. Once found, we connect them.
Here's how the algorithm would work step-by-step:
class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
self.next = None
def connect_nodes_brute_force(root):
if not root:
return root
current_level_nodes = [root]
while current_level_nodes:
level_size = len(current_level_nodes)
for i in range(level_size):
current_node = current_level_nodes[i]
# Finding right neighbor node
for j in range(i + 1, level_size):
right_neighbor = current_level_nodes[j]
# Connect the node to its right neighbor
current_node.next = right_neighbor
break
next_level_nodes = []
for node in current_level_nodes:
if node.left:
next_level_nodes.append(node.left)
if node.right:
next_level_nodes.append(node.right)
current_level_nodes = next_level_nodes
return root
We want to connect each node in a perfect binary tree to its neighbor on the same level. The key idea is to use existing connections to efficiently traverse each level without extra memory, almost like an assembly line.
Here's how the algorithm would work step-by-step:
class Node:
def __init__(self, val=0, left=None, right=None, next=None):
self.val = val
self.left = left
self.right = right
self.next = next
def connect(root: Node) -> Node:
if not root:
return root
leftmost_node = root
while leftmost_node:
current_node = leftmost_node
while current_node:
# Connect left child to right child.
if current_node.left:
current_node.left.next = current_node.right
# Connect right child to next node's left child.
if current_node.next:
current_node.right.next = current_node.next.left
# Move to the next node on the same level.
current_node = current_node.next
# Move to the next level.
# Ensures the process repeats for subsequent levels.
leftmost_node = leftmost_node.left
return root
Case | How to Handle |
---|---|
Null root node | If the root is null, there is nothing to connect, so return null immediately. |
Perfect binary tree with only one level (root only) | Root node's next pointer should remain null since it has no siblings. |
Skewed binary tree (e.g., all nodes on left side) | Breadth-first or level-order traversal must correctly identify sibling at each level even in unbalanced cases. |
Complete binary tree of maximum possible height (considering memory limits) | Ensure the algorithm uses memory efficiently and doesn't cause stack overflow (for recursive solutions) or exceed available memory (for queue-based solutions). |
Binary tree where the connection between levels is the most complex | Level order or BFS solution accounts for all levels without special handling by using a queue. |
Binary tree with identical node values | The algorithm should correctly link next pointers regardless of the node values. |
Tree has only left children for certain nodes | The algorithm must correctly handle cases where right child doesn't exist, appropriately finding the next node or setting null. |
Input is a malformed binary tree (cycles or disconnected subtrees - though unlikely) | Assume input is a valid binary tree as stated by prompt requirements. |