Average of Levels in Binary Tree
LeetCode 637 · সহজ · সমাধান, intuition ও ধাপে ধাপে ওয়াকথ্রু
BFS with level size; average per level.
আমি 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
Queue with the root.
- 2
For each level, pop size nodes, sum values, enqueue children.
- 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 resAverage 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.