-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0501-find-mode-in-binary-search-tree.py
More file actions
43 lines (29 loc) · 921 Bytes
/
0501-find-mode-in-binary-search-tree.py
File metadata and controls
43 lines (29 loc) · 921 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#Time complexity:O(n)
#Space complexity: O(n)
from collections import defaultdict
from typing import List, Optional
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def findMode(self, root: Optional[TreeNode]) -> List[int]:
def dfs(node: Optional[TreeNode], counter):
if not node:
return
counter[node.val] += 1
dfs(node.left, counter)
dfs(node.right, counter)
counter = defaultdict(int)
dfs(root, counter)
res = []
maxFrequencies = max(counter.values())
for key in counter:
if maxFrequencies == counter[key]:
res.append(key)
return res
root = TreeNode(1)
root.right = TreeNode(3)
root.right.left = TreeNode(2)
print(Solution().findMode(root))