Skip to content

Commit a46f960

Browse files
authored
Create average-of-levels-in-binary-tree.py
1 parent e6174d2 commit a46f960

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
# Time: O(n)
2+
# Space: O(h)
3+
4+
# Given a non-empty binary tree,
5+
# return the average value of the nodes on each level in the form of an array.
6+
#
7+
# Example 1:
8+
# Input:
9+
# 3
10+
# / \
11+
# 9 20
12+
# / \
13+
# 15 7
14+
# Output: [3, 14.5, 11]
15+
# Explanation:
16+
# The average value of nodes on level 0 is 3,
17+
# on level 1 is 14.5, and on level 2 is 11. Hence return [3, 14.5, 11].
18+
#
19+
# Note:
20+
# The range of node's value is in the range of 32-bit signed integer.
21+
22+
# Definition for a binary tree node.
23+
# class TreeNode(object):
24+
# def __init__(self, x):
25+
# self.val = x
26+
# self.left = None
27+
# self.right = None
28+
29+
class Solution(object):
30+
def averageOfLevels(self, root):
31+
"""
32+
:type root: TreeNode
33+
:rtype: List[float]
34+
"""
35+
result = []
36+
q = collections.deque([root])
37+
while q:
38+
total, count = 0, 0
39+
next_q = collections.deque([])
40+
while q:
41+
n = q.popleft()
42+
total += n.val;
43+
count += 1
44+
if n.left:
45+
next_q.append(n.left)
46+
if n.right:
47+
next_q.append(n.right)
48+
q, next_q = next_q, q
49+
result.append(float(total) / count)
50+
return result

0 commit comments

Comments
 (0)