Skip to content

Commit 225d071

Browse files
solves average levels of binary tree in python
1 parent 867286a commit 225d071

File tree

2 files changed

+35
-1
lines changed

2 files changed

+35
-1
lines changed

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -165,7 +165,7 @@
165165
| 624 | 🔒 [Maximum Distance in Arrays](https://leetcode.com/problems/maximum-distance-in-arrays) | |
166166
| 628 | [Maximum Product of Three Numbers](https://leetcode.com/problems/maximum-product-of-three-numbers) | [![Java](assets/java.png)](src/MaximumProductOfThreeNumbers.java) [![Python](assets/python.png)](python/maximum_product_of_three_numbers.py) |
167167
| 633 | [Sum Square Numbers](https://leetcode.com/problems/sum-of-square-numbers) | [![Java](assets/java.png)](src/SumOfSquareNumbers.java) [![Python](assets/python.png)](python/sum_of_squares_numbers.py) |
168-
| 637 | [Average of Levels in Binary Tree](https://leetcode.com/problems/average-of-levels-in-binary-tree) | [![Java](assets/java.png)](src/AverageLevelsOfBinaryTree.java) [![Python](assets/python.png)](python/)
168+
| 637 | [Average of Levels in Binary Tree](https://leetcode.com/problems/average-of-levels-in-binary-tree) | [![Java](assets/java.png)](src/AverageLevelsOfBinaryTree.java) [![Python](assets/python.png)](python/average_levels_of_binary_tree.py)
169169
| 643 | [Maximum Average SubArray I](https://leetcode.com/problems/maximum-average-subarray-i) | [![Java](assets/java.png)](src/MaximumAverageSubArrayI.java) [![Python](assets/python.png)](python/maximum_average_subarray_I.py) |
170170
| 645 | [Set Mismatch](https://leetcode.com/problems/set-mismatch) | [![Java](assets/java.png)](src/SetMismatch.java) [![Python](assets/python.png)](python/set_mismatch.py) |
171171
| 653 | [Two Sum IV - Input is a BST](https://leetcode.com/problems/two-sum-iv-input-is-a-bst) | [![Java](assets/java.png)](src/TwoSumIVInputIsABST.java) [![Python](assets/python.png)](python/two_sum_iv.py) |
+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
# Definition for a binary tree node.
2+
from typing import List
3+
from collections import deque
4+
5+
6+
class TreeNode:
7+
def __init__(self, val=0, left=None, right=None):
8+
self.val = val
9+
self.left = left
10+
self.right = right
11+
12+
13+
class Solution:
14+
def averageOfLevels(self, root: TreeNode) -> List[float]:
15+
result = [0]
16+
queue = deque()
17+
queue.append(root)
18+
queue.append(None)
19+
count = 0
20+
while queue:
21+
current = queue.popleft()
22+
if current is None and len(queue) == 0: break
23+
if current is None:
24+
queue.append(None)
25+
result[-1] /= count
26+
result.append(0)
27+
count = 0
28+
continue
29+
count += 1
30+
if current.left is not None: queue.append(current.left)
31+
if current.right is not None: queue.append(current.right)
32+
result[-1] += current.val
33+
result[-1] /= count
34+
return result

0 commit comments

Comments
 (0)