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

मैंने 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.