Skip to content

Populating Next Right Pointers in Each Node II

Given a binary tree (not necessarily perfect), 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.

InputOutputExplanation
[1,2,3,4,5,null,7]Next pointers at level 2 connect 4→5 and 5→7Nodes at same level connected; null skipped
[1,2,3]Simple tree: level 2 has 2→3Both nodes present, connection straightforward
  • The number of nodes is in the range [0, 6000].
  • -100 <= Node.val <= 100
ApproachTimeSpaceBest When
Level-Order QueueO(n)O(w)Simple, clear level traversal; w is max width
Pre-Computed LinksO(n)O(1)Memory-constrained; use parent-level links to traverse
  • Learn Level-Order Queue first — it is straightforward and intuitive.
  • Study Pre-Computed Links to master O(1) space without extra queue.
O(1) Space Optimal
Pre-Computed Links
O(n) time · O(1) space
Clear & Intuitive
Level-Order Queue
O(n) time · O(w) space
★ Recommended

Use a queue to process nodes level-by-level. For each level, connect consecutive nodes’ next pointers.

⏱ Time O(n) Visit each node once 💾 Space O(w) Queue stores max level width

Input: [1,2,3,4,5,null,7]

StepActionResult
Level 0Process node 1Node 1 next = NULL
Level 1Process nodes 2, 3Connect 2 → 3
Level 2Process nodes 4, 5, 7Connect 4 → 5 → 7 (skip null)
function connect(root):
if not root: return root
queue = [root]
while queue not empty:
levelSize = queue.length
prev = null
for i in 0..levelSize-1:
node = queue.pop()
if prev: prev.next = node
prev = node
if node.left: queue.push(node.left)
if node.right: queue.push(node.right)
return root
populating_next_right_pointers_ii_queue.py
from typing import Optional
from collections import deque
# 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
def connect(root: Optional[Node]) -> Optional[Node]:
"""
Populates next pointers in a perfect binary tree using level-order BFS queue.
Time: O(n), Space: O(w) where w is max width
"""
if not root:
return root
queue = deque([root])
while queue:
level_size = len(queue)
prev = None
for i in range(level_size):
node = queue.popleft()
if prev:
prev.next = node
prev = node
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return root
# Test cases
if __name__ == "__main__":
# Example 1: Perfect binary tree
root = Node(1,
Node(2, Node(4), Node(5)),
Node(3, Node(6), Node(7)))
result = connect(root)
print("Example 1: Tree with next pointers connected via queue")
# Example 2: Single node
single = Node(1)
result = connect(single)
print("Example 2: Single node tree")
# Example 3: None
result = connect(None)
print("Example 3: None input")
optimal

Use next pointers from the parent level to traverse the current level, eliminating the queue.

⏱ Time O(n) Visit each node once 💾 Space O(1) Only pointers, no extra storage

Input: [1,2,3,4,5,null,7]

StepUsingConnects
Level 1root’s structure2 → 3
Level 22.next (= 3)4 → 5 → 7
function connect(root):
if not root: return root
leftmost = root
while leftmost:
prev = null
current = leftmost
while current:
if current.left:
if prev: prev.next = current.left
prev = current.left
if current.right:
if prev: prev.next = current.right
prev = current.right
current = current.next
leftmost = leftmost.left
return root
populating_next_right_pointers_ii_precomputed_links.py
from typing import Optional
# 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
def connect(root: Optional[Node]) -> Optional[Node]:
"""
Populates next pointers using pre-computed links without extra queue.
Uses next pointers of parent level to traverse current level.
Time: O(n), Space: O(1)
"""
if not root:
return root
leftmost = root
while leftmost:
prev = None
current = leftmost
while current:
if current.left:
if prev:
prev.next = current.left
prev = current.left
if current.right:
if prev:
prev.next = current.right
prev = current.right
current = current.next
leftmost = leftmost.left
return root
# Test cases
if __name__ == "__main__":
# Example 1: Perfect binary tree
root = Node(1,
Node(2, Node(4), Node(5)),
Node(3, Node(6), Node(7)))
result = connect(root)
print("Example 1: Tree with next pointers connected via pre-computed links")
# Example 2: Single node
single = Node(1)
result = connect(single)
print("Example 2: Single node tree")
# Example 3: None
result = connect(None)
print("Example 3: None input")