#116

Populating Next Right Pointers in Each Node

Medium
Linked ListTreeDepth-First SearchBreadth-First SearchBinary TreeTwo PointersLevel Order Traversal
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

This approach leverages the perfect structure of the binary tree to connect nodes using existing pointers without additional space. We use a pointer to traverse the current level and connect nodes directly.

⚙️

Algorithm

3 steps
  1. 1Step 1: Start from the root node and set a pointer to the leftmost node of the current level.
  2. 2Step 2: While there are nodes at the current level, connect the left and right children of each node.
  3. 3Step 3: Move the pointer to the next node at the same level until all nodes are processed.
solution.py21 lines
1# Full working Python code
2class Node:
3    def __init__(self, val=0, left=None, right=None, next=None):
4        self.val = val
5        self.left = left
6        self.right = right
7        self.next = next
8
9def connect(root):
10    if not root:
11        return
12    leftmost = root
13    while leftmost.left:
14        current = leftmost
15        while current:
16            current.left.next = current.right
17            if current.next:
18                current.right.next = current.next.left
19            current = current.next
20        leftmost = leftmost.left
21

Complexity note: The time complexity is linear because we visit each node exactly once. The space complexity is constant since we use only a few pointers and do not utilize additional data structures.

  • 1The tree is perfect, meaning all levels are fully filled, which allows for direct connections.
  • 2Using existing pointers to connect nodes saves space and improves efficiency.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.