Populating Next Right Pointers in Each Node
LeetCode 116 · நடுத்தரம் · தீர்வு, intuition & படிப்படியான வாக்த்ரூ
Level-order BFS; next = following node in the level.
நான் Populating Next Right Pointers in Each Node (LeetCode 116) ஐ இப்படித் தீர்த்தேன் — BFS / Level Order பேட்டர்னின் ஒரு நடுத்தரம் பிராப்ளம். கீழே: intuition, படிப்படியான approach, என் accepted Python கோட், animated test cases மற்றும் line-by-line debugger.
கீழேயுள்ள விளக்கம் ஆங்கிலத்தில் உள்ளது.
Intuition
Within a BFS level, every node's next pointer is simply the node dequeued after it. Process the queue level by level and link each node to the queue's new front, except the last node of the level.
Approach
- 1
Queue with the root.
- 2
For each level of size k, pop nodes in order.
- 3
For all but the last, node.next = queue[0].
- 4
Enqueue children.
நான் எப்படித் தீர்த்தேன்
Level-order BFSPythonO(n) time · O(n) space
class Solution:
def connect(self, root):
if root is None:
return root
queue = [root]
while queue:
size = len(queue)
for i in range(size):
node = queue.pop(0)
if i < size - 1:
node.next = queue[0]
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return rootPopulating Next Right Pointers in Each Node — அடிக்கடி கேட்கப்படும் கேள்விகள்
Populating Next Right Pointers in Each Node பின்னாலுள்ள intuition என்ன?
Within a BFS level, every node's next pointer is simply the node dequeued after it. Process the queue level by level and link each node to the queue's new front, except the last node of the level.
Populating Next Right Pointers in Each Node (LeetCode 116) ஐ எப்படித் தீர்ப்பது?
1. Queue with the root. 2. For each level of size k, pop nodes in order. 3. For all but the last, node.next = queue[0]. 4. Enqueue children.
Populating Next Right Pointers in Each Node இன் time மற்றும் space complexity என்ன?
Time: O(n). Space: O(n). (Accepted approach: Level-order BFS.)
Populating Next Right Pointers in Each Node இல் பொதுவான தவறுகள் என்ன?
The perfect-tree version can be done in O(1) space using the next pointers of the level above.