Skip to content

Commit 622ab73

Browse files
committed
D. J.:
- Added the leetcode problem and solution for 637 Average of Levels in Binary Tree
1 parent ee2ef59 commit 622ab73

File tree

3 files changed

+50
-0
lines changed

3 files changed

+50
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,7 @@ This repository contains awesome LeetCode problems and solutions written in Pyth
7373
- [383 Ransom Note](https://leetcode.com/problems/ransom-note/description/)
7474
- [392 Is Subsequence](https://leetcode.com/problems/is-subsequence/description/)
7575
- [452 Minimum Number of Arrows to Burst Balloons](https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/description/)
76+
- [637 Average of Levels in Binary Tree](https://leetcode.com/problems/average-of-levels-in-binary-tree/description/)
7677

7778
## Development 🔧
7879

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
from typing import List, Optional
2+
3+
from awesome_python_leetcode.tree import TreeNode
4+
5+
6+
class Solution:
7+
def averageOfLevels(self, root: Optional[TreeNode]) -> List[float]:
8+
"""
9+
Given the root of a binary tree, return the average value of the nodes on each
10+
level in the form of an array. Answers within 10-5 of the actual answer will be
11+
accepted.
12+
"""
13+
parents = [root]
14+
result = []
15+
while parents:
16+
# Build average value
17+
total_sum = 0
18+
for p in parents:
19+
total_sum += p.val
20+
result.append(total_sum / len(parents))
21+
22+
# Build childs
23+
childs = []
24+
for p in parents:
25+
if p.left:
26+
childs.append(p.left)
27+
if p.right:
28+
childs.append(p.right)
29+
parents = childs
30+
return result
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
from typing import List
2+
3+
import pytest
4+
5+
from awesome_python_leetcode._637_average_of_levels_in_binary_tree import Solution
6+
from awesome_python_leetcode.tree import TreeNode
7+
8+
9+
@pytest.mark.parametrize(
10+
argnames=["root", "expected"],
11+
argvalues=[
12+
([3, 9, 20, None, None, 15, 7], [3.00000, 14.50000, 11.00000]),
13+
([3, 9, 20, 15, 7], [3.00000, 14.50000, 11.00000]),
14+
],
15+
)
16+
def test_func(root: List[int], expected: List[float]):
17+
root = TreeNode.build(root)
18+
average_of_levels = Solution().averageOfLevels(root)
19+
assert average_of_levels == expected

0 commit comments

Comments
 (0)