[Leetcode] Binary tree-- 637. Average of Levels in Binary Tree

Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array.

Example 1:

Input:
    3
   / \
  9  20
    /  \
   15   7
Output: [3, 14.5, 11]
Explanation:
The average value of nodes on level 0 is 3,  on level 1 is 14.5, and on level 2 is 11. Hence return [3, 14.5, 1


Solution:

   # it actually examines the knowledge of level order
   #refer to the similar problem : 102. Binary Tree Level Order Traversal

 1         if not root:
 2             return []
 3         d = collections.deque()
 4         d.append(root)
 5         resLst = []
 6         while(len(d)):
 7             n = len(d)
 8             lst = []
 9             tmpSum = 0.0
10             count = n
11             while(n > 0):
12                 node = d.popleft()
13                 tmpSum += node.val
14                 if node.left:
15                     d.append(node.left)
16                 if node.right:
17                     d.append(node.right)
18                 n -= 1
19             resLst.append(tmpSum/count)
20 
21         return resLst

 

posted @ 2017-07-26 14:06  安新  阅读(133)  评论(0编辑  收藏  举报