Skip to content

Commit fd10538

Browse files
committed
Runtime: 31 ms (Top 99.88%) | Memory: 19.20 MB (Top 96.36%)
1 parent 5f634d6 commit fd10538

File tree

1 file changed

+38
-20
lines changed

1 file changed

+38
-20
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,41 @@
1-
# Runtime: 30 ms (Top 89.5%) | Memory: 20.95 MB (Top 77.8%)
2-
3-
class Solution(object):
4-
prev = None
5-
max_count = 0
6-
current_count = 0
7-
result = []
1+
// Runtime: 31 ms (Top 99.88%) | Memory: 19.20 MB (Top 96.36%)
82

3+
class Solution:
94
def findMode(self, root):
10-
self.dfs(root)
11-
return self.result
5+
curr_node = root
6+
result = []
7+
curr_streak = 0
8+
curr_num = float("inf")
9+
max_streak = 0
1210

13-
def dfs(self, node):
14-
if not node: return
15-
self.dfs(node.left)
16-
self.current_count = 1 if node.val != self.prev else self.current_count + 1
17-
if self.current_count == self.max_count:
18-
self.result.append(node.val)
19-
elif self.current_count > self.max_count:
20-
self.result = [node.val]
21-
self.max_count = self.current_count
22-
self.prev = node.val
23-
self.dfs(node.right)
11+
while curr_node:
12+
if curr_node.left:
13+
neighbor = curr_node.left
14+
while neighbor.right is not None:
15+
neighbor = neighbor.right
16+
neighbor.right = curr_node
17+
18+
tmp = curr_node.left
19+
curr_node.left = None
20+
curr_node = tmp
21+
else:
22+
# since we deleted the left pointer when we were done processing in the previous if-block,
23+
# we know that we only reach this else case
24+
# if we've already processed this node.
25+
# Therefore, do the value processing here
26+
# and move to the right neighbor afterward
27+
if curr_node.val == curr_num:
28+
curr_streak += 1
29+
else:
30+
curr_streak = 0
31+
curr_num = curr_node.val
32+
33+
if curr_streak == max_streak:
34+
result.append(curr_num)
35+
elif curr_streak > max_streak:
36+
max_streak = curr_streak
37+
result = [curr_num]
38+
39+
curr_node = curr_node.right
40+
41+
return result

0 commit comments

Comments
 (0)