forked from csujedihy/lc-all-solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfind-mode-in-binary-search-tree.py
41 lines (37 loc) · 1.14 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
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def findMode(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
def visit(v):
if v != self.pre:
self.pre = v
self.cnt = 0
self.cnt += 1
if self.cnt > self.maxFreq:
self.maxFreq = self.cnt
self.modeCnt = 1
elif self.cnt == self.maxFreq:
if self.ans:
self.ans[self.modeCnt] = v
self.modeCnt += 1
def inorder(root):
if root:
inorder(root.left)
visit(root.val)
inorder(root.right)
self.pre = None
self.ans = None
self.maxFreq = self.modeCnt = self.cnt = 0
inorder(root)
self.ans = [0] * self.modeCnt
self.modeCnt = self.cnt = 0
inorder(root)
return self.ans