Skip to content

Commit

Permalink
"Find Mode in Binary Search Tree" solution
Browse files Browse the repository at this point in the history
  • Loading branch information
lancelote committed Nov 1, 2023
1 parent f39b358 commit 5bd43c0
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
32 changes: 32 additions & 0 deletions src/find_mode_in_binary_search_tree.py
Original file line number Diff line number Diff line change
@@ -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
16 changes: 16 additions & 0 deletions tests/test_find_mode_in_binary_search_tree.py
Original file line number Diff line number Diff line change
@@ -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

0 comments on commit 5bd43c0

Please sign in to comment.