Tensorum
YouTubeಕಲಿಯಲು ಪ್ರಾರಂಭಿಸಿ
LeetCode 637 · Tree

Average of Levels in Binary Tree

LeetCode 637 · ಸುಲಭ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್‌ಥ್ರೂ

BFS with level size; average per level.

ಸುಲಭTreeDepth-First SearchBreadth-First SearchBinary Tree
LeetCode ನಲ್ಲಿ ತೆರೆಯಿರಿ ↗

ನಾನು Average of Levels in Binary Tree (LeetCode 637) ಅನ್ನು ಹೀಗೆ ಪರಿಹರಿಸಿದೆ — Tree ಪ್ಯಾಟರ್ನ್‌ನ ಒಂದು ಸುಲಭ ಪ್ರಾಬ್ಲಮ್. ಕೆಳಗೆ: intuition, ಹಂತ ಹಂತದ approach, ನನ್ನ accepted Python ಕೋಡ್, animated test cases ಮತ್ತು line-by-line debugger.

ಕೆಳಗಿನ ವಿವರಣೆ ಇಂಗ್ಲಿಷ್‌ನಲ್ಲಿದೆ.

Intuition

Level-order BFS processes one level at a time: sum the values of the nodes in the current queue snapshot and divide by how many there are.

Approach

  1. 1

    Queue with the root.

  2. 2

    For each level, pop size nodes, sum values, enqueue children.

  3. 3

    Append sum / size.

ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ

Level-order BFSPythonO(n) time
class Solution:
    def averageOfLevels(self, root):
        queue = [root]
        res = []
        while queue:
            size = len(queue)
            total = 0
            for i in range(size):
                node = queue.pop(0)
                if node is None:
                    continue
                total += node.val
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
            res.append(total / size)
        return res
ಸ್ಟೆಪ್-ಥ್ರೂ ಲೋಡ್ ಆಗುತ್ತಿದೆ…

Average of Levels in Binary Tree — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು

Average of Levels in Binary Tree ಹಿಂದಿನ intuition ಏನು?

Level-order BFS processes one level at a time: sum the values of the nodes in the current queue snapshot and divide by how many there are.

Average of Levels in Binary Tree (LeetCode 637) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?

1. Queue with the root. 2. For each level, pop size nodes, sum values, enqueue children. 3. Append sum / size.

Average of Levels in Binary Tree ನ time ಮತ್ತು space complexity ಎಷ್ಟು?

Time: O(n). Space: O(n). (Accepted approach: Level-order BFS.)

Average of Levels in Binary Tree ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?

Use floating-point division.