diff --git a/src/find_mode_in_binary_search_tree.py b/src/find_mode_in_binary_search_tree.py new file mode 100644 index 0000000..6d52ff9 --- /dev/null +++ b/src/find_mode_in_binary_search_tree.py @@ -0,0 +1,32 @@ +import typing as t +from collections import Counter + +from src.utils.binary_tree import TreeNode + + +class Solution: + def findMode(self, root: TreeNode | None) -> list[int]: + counter: t.Counter[int] = Counter() + + def dfs(node: TreeNode | None) -> None: + if node is None: + return + + counter[node.val] += 1 + + dfs(node.left) + dfs(node.right) + + dfs(root) + + result: list[int] = [] + + [(_, most_common)] = counter.most_common(1) + + for x, count in counter.most_common(): + if count == most_common: + result.append(x) + else: + break + + return result diff --git a/tests/test_find_mode_in_binary_search_tree.py b/tests/test_find_mode_in_binary_search_tree.py new file mode 100644 index 0000000..32000ad --- /dev/null +++ b/tests/test_find_mode_in_binary_search_tree.py @@ -0,0 +1,16 @@ +import pytest + +from src.find_mode_in_binary_search_tree import Solution +from src.utils.binary_tree import list_to_tree + + +@pytest.mark.parametrize( + "in_list,expected", + ( + ([1, None, 2, 2], [2]), + ([0], [0]), + ), +) +def test_solution(in_list, expected): + root = list_to_tree(in_list) + assert Solution().findMode(root) == expected