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.