Skip to content

Commit 5bd43c0

Browse files
committed
"Find Mode in Binary Search Tree" solution
1 parent f39b358 commit 5bd43c0

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
import typing as t
2+
from collections import Counter
3+
4+
from src.utils.binary_tree import TreeNode
5+
6+
7+
class Solution:
8+
def findMode(self, root: TreeNode | None) -> list[int]:
9+
counter: t.Counter[int] = Counter()
10+
11+
def dfs(node: TreeNode | None) -> None:
12+
if node is None:
13+
return
14+
15+
counter[node.val] += 1
16+
17+
dfs(node.left)
18+
dfs(node.right)
19+
20+
dfs(root)
21+
22+
result: list[int] = []
23+
24+
[(_, most_common)] = counter.most_common(1)
25+
26+
for x, count in counter.most_common():
27+
if count == most_common:
28+
result.append(x)
29+
else:
30+
break
31+
32+
return result
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.find_mode_in_binary_search_tree import Solution
4+
from src.utils.binary_tree import list_to_tree
5+
6+
7+
@pytest.mark.parametrize(
8+
"in_list,expected",
9+
(
10+
([1, None, 2, 2], [2]),
11+
([0], [0]),
12+
),
13+
)
14+
def test_solution(in_list, expected):
15+
root = list_to_tree(in_list)
16+
assert Solution().findMode(root) == expected

0 commit comments

Comments
 (0)