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.