-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathfind_mode_in_binary_search_tree.py
More file actions
37 lines (31 loc) · 1014 Bytes
/
find_mode_in_binary_search_tree.py
File metadata and controls
37 lines (31 loc) · 1014 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
# Definition for a binary tree node.
from typing import List
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def __init__(self):
self.count = 1
self.previous = None
self.max = 0
def find_mode(self, root: TreeNode, modes: List[int]):
if root is None:
return
self.find_mode(root.left, modes)
if self.previous:
self.count = self.count + 1 if root.val == self.previous.val else 1
if self.count > self.max:
self.max = self.count
modes.clear()
modes.append(root.val)
elif self.count == self.max:
modes.append(root.val)
self.previous = root
self.find_mode(root.right, modes)
def findMode(self, root: TreeNode) -> List[int]:
if root is None: return []
result = []
self.find_mode(root, result)
return result