-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
"Find Mode in Binary Search Tree" solution
- Loading branch information
Showing
2 changed files
with
48 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |