您的位置:首页 > 其它

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

2017-08-11 12:58 585 查看
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


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: