117. Populating Next Right Pointers in Each Node II ๐
Last updated
Last updated
Difficulty: Medium
- Tags: Binary Tree
, Breadth-First Search (BFS)
, Linked List
Given a binary tree:
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:
Output:
Explanation:
Given the tree:
The next
pointers should connect nodes as:
๐น Example 2:
Input:
Output:
The number of nodes in the tree is in the range [0, 6000]
.
-100 <= Node.val <= 100
.
You may only use constant extra space.
The recursive approach is fine. You may assume implicit stack space does not count as extra space for this problem.
To solve this problem:
Use a level-order traversal to connect nodes at the same level.
For the constant space requirement, use a dummy node to traverse each level without additional data structures.
Dummy Node Approach:
Use a dummy node to build the next
pointers for the next level.
Traverse each level, connecting child nodes to the dummy node.
Level Traversal:
Move through the current level using next
pointers.
Update the next
pointers of child nodes to establish connections.
Space Efficiency:
The solution uses constant space by avoiding auxiliary data structures like queues.
O(n): Each node is visited exactly once.
O(1): No additional space is used beyond the dummy node and pointers.
Could you adapt this solution for a more generalized graph structure?
How would the solution change if the binary tree could contain cycles?
You can find the full solution here.