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.