Skip to content

Commit d524477

Browse files
committed
"Count Nodes Equal to Average of Subtree" solution
1 parent 5bd43c0 commit d524477

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
from src.utils.binary_tree import TreeNode
2+
3+
4+
class Solution:
5+
def averageOfSubtree(self, root: TreeNode | None) -> int:
6+
count = 0
7+
8+
def dfs(node: TreeNode | None) -> tuple[int, int]:
9+
nonlocal count
10+
11+
if node is None:
12+
return 0, 0
13+
14+
left_count, left_total = dfs(node.left)
15+
right_count, right_total = dfs(node.right)
16+
17+
local_count = 1 + left_count + right_count
18+
local_total = node.val + left_total + right_total
19+
20+
if int(local_total / local_count) == node.val:
21+
count += 1
22+
23+
return local_count, local_total
24+
25+
dfs(root)
26+
return count
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import pytest
2+
3+
from src.count_nodes_equal_to_average_of_subtree import Solution
4+
from src.utils.binary_tree import list_to_tree
5+
6+
7+
@pytest.mark.parametrize(
8+
"in_list,expected",
9+
(
10+
([4, 8, 5, 0, 1, None, 6], 5),
11+
([1], 1),
12+
),
13+
)
14+
def test_solution(in_list, expected):
15+
root = list_to_tree(in_list)
16+
assert Solution().averageOfSubtree(root) == expected

0 commit comments

Comments
 (0)