#117
Populating Next Right Pointers in Each Node II
MediumLinked ListTreeDepth-First SearchBreadth-First SearchBinary TreeTwo PointersLevel Order Traversal
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution uses a constant space approach by leveraging the next pointers already established. We traverse the tree level by level, using the next pointers to connect nodes without needing additional data structures.
⚙️
Algorithm
3 steps- 1Step 1: Start from the root and initialize a pointer to track the current node at the current level.
- 2Step 2: For each node, connect its left and right children to the next node in the same level using the next pointers.
- 3Step 3: Move to the next level using the established next pointers.
solution.py30 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:
14 curr = leftmost
15 leftmost = None
16 prev = None
17 while curr:
18 if curr.left:
19 if prev:
20 prev.next = curr.left
21 else:
22 leftmost = curr.left
23 prev = curr.left
24 if curr.right:
25 if prev:
26 prev.next = curr.right
27 else:
28 leftmost = curr.right
29 prev = curr.right
30 curr = curr.nextℹ
Complexity note: The time complexity is O(n) because we visit each node exactly once. The space complexity is O(1) because we are using only a constant amount of extra space, leveraging the existing next pointers.
- 1Using next pointers can help reduce space complexity.
- 2Level-order traversal is key to connecting nodes in the same level.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.