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.