Home > AI > Data Structure > Tree >

leetcode-637-Average of Levels in Binary Tree

Solution: Python

class Solution:
   
    def averageOfLevels(self, root: TreeNode) -> List[float]:
        if root is None:
            return 
    
        re = []
        q = [root]
        while q:
            tmpLen = len(q)
            levelList = []
            for i in range(tmpLen):
                tmp = q.pop(0)
                levelList.append(tmp.val)
                if tmp.left:
                    q.append(tmp.left)
                if tmp.right:
                    q.append(tmp.right)
            re.append(sum(levelList) / len(levelList))
        return re

Leave a Reply