Find Mode in Binary Search Tree LeetCode solution in Python

1
class Solution:
2
def findMode(self, root):
3
curr_node = root
4
result = []
5
curr_streak = 0
6
curr_num = float("inf")
7
max_streak = 0
8

9
while curr_node:
10
if curr_node.left:
11
neighbor = curr_node.left
12
while neighbor.right is not None:
13
neighbor = neighbor.right
14
neighbor.right = curr_node
15

16
tmp = curr_node.left
17
curr_node.left = None
18
curr_node = tmp
19
else:
20
# since we deleted the left pointer when we were done processing in the previous if-block,
21
# we know that we only reach this else case
22
# if we've already processed this node.
23
# Therefore, do the value processing here
24
# and move to the right neighbor afterward
25
if curr_node.val == curr_num:
26
curr_streak += 1
27
else:
28
curr_streak = 0
29
curr_num = curr_node.val
30

31
if curr_streak == max_streak:
32
result.append(curr_num)
33
elif curr_streak > max_streak:
34
max_streak = curr_streak
35
result = [curr_num]
36

37
curr_node = curr_node.right
38

39
return result

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0