Python Solution with Level Order Traversal 79ms


  • 0
    L
    class Solution(object):
        def averageOfLevels(self, root):
            if not root:return 
            level_count = []                        # 下标对应树的层,存放每层节点个数
            level_sum = []                          # 下标对应树的层,存放每层节点值之和
            Qnode = []
            
            Qnode.append((root,0))                  # 入队时,将节点与其层数一起入队
            while len(Qnode):
                t = Qnode.pop(0)                    # 出队时,读取数据
                if len(level_count) <= t[1]:        # 如果是第一次出队该层节点
                    level_count.append(1)
                    level_sum.append(t[0].val)
                else:
                    level_count[t[1]] += 1
                    level_sum[t[1]] += t[0].val
                if t[0].left:                       # 子节点不为None则入队
                    Qnode.append((t[0].left,t[1]+1))
                if t[0].right:
                    Qnode.append((t[0].right,t[1]+1))
                    
            return [level_sum[i]/float(level_count[i]) for i in range(len(level_count))]
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.