Skip to content

637. Average of Levels in Binary Tree

637. Average of Levels in Binary Tree

Companies: Facebook
Date: September 8, 2021
Difficulty: Easy
LeetCode link: https://leetcode.com/problems/average-of-levels-in-binary-tree/
Review Date: October 3, 2021
Status: Done
Tags: BFS, Binary Tree

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def averageOfLevels(self, root: Optional[TreeNode]) -> List[float]:

                # Put each node in current level
                # Track their sum and count
                # Add their child nodes into next level
                # once current level is finished, set currentLevel[] :=nextLevel[]

        if not root:
            return []

        sumForThisLevel = 0
        numNodesThisLevel = 0

        nodesInThisLevel = [root]
        nodesInNextLevel = []

        averages = []

        while nodesInThisLevel or nodesInNextLevel:

            if not nodesInThisLevel:
                averages.append(sumForThisLevel / numNodesThisLevel)
                nodesInThisLevel = nodesInNextLevel
                nodesInNextLevel = []
                sumForThisLevel = 0
                numNodesThisLevel = 0
                continue

            current = nodesInThisLevel.pop(0)

            print(current.val)

            sumForThisLevel += current.val
            numNodesThisLevel += 1

            if current.left:
                nodesInNextLevel.append(current.left)
            if current.right:
                nodesInNextLevel.append(current.right)

        averages.append(sumForThisLevel / numNodesThisLevel)
        return averages

Last update : 25 mai 2024
Created : 25 mai 2024