-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfind-mode-in-binary-search-tree.py
46 lines (37 loc) · 1.07 KB
/
find-mode-in-binary-search-tree.py
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
44
45
46
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def findMode(self, root: TreeNode) -> List[int]:
ans = []
max_count = 0
count = 0
temp = None
def update(node):
nonlocal count
nonlocal max_count
nonlocal ans
if count == max_count:
ans.append(node.val)
elif count > max_count:
max_count = count
ans = [node.val]
def ldr(node):
nonlocal temp
nonlocal count
if not node:
return
ldr(node.left)
if node.val == temp:
count += 1
update(node)
else:
temp = node.val
count = 1
update(node)
ldr(node.right)
ldr(root)
return ans