Tensorum
YouTubeనేర్చుకోవడం ప్రారంభించండి
LeetCode 116 · BFS / Level Order

Populating Next Right Pointers in Each Node

LeetCode 116 · మధ్యస్థం · పరిష్కారం, intuition & దశలవారీ వాక్‌త్రూ

Level-order BFS; next = following node in the level.

మధ్యస్థంLinked ListTreeDepth-First SearchBreadth-First SearchBinary Tree
LeetCode లో తెరవండి ↗

నేను 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. 1

    Queue with the root.

  2. 2

    For each level of size k, pop nodes in order.

  3. 3

    For all but the last, node.next = queue[0].

  4. 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 root
స్టెప్-త్రూ లోడ్ అవుతోంది…

Populating 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.