Skip to content

Commit 680d17e

Browse files
committed
Time: 208 ms (90.66%), Space: 38.4 MB (94.58%) - LeetHub
1 parent f0e38e3 commit 680d17e

File tree

1 file changed

+49
-14
lines changed

1 file changed

+49
-14
lines changed
Lines changed: 49 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,55 @@
11
class Solution {
2-
private val counter = mutableMapOf<Int, Int>()
3-
4-
private fun TreeNode?.count() {
5-
if (this == null)
6-
return
7-
counter[this.`val`] = (counter[this.`val`] ?: 0) + 1
8-
left.count()
9-
right.count()
2+
private fun morris(root: TreeNode): MutableList<Int> {
3+
var currentStreak = 0
4+
var currentVal = Int.MIN_VALUE
5+
var maxStreak = 0
6+
val result = mutableListOf<Int>()
7+
8+
var current: TreeNode? = root
9+
while (current != null) {
10+
if (current.left != null) {
11+
// connect rightmost leaf of left subtree to current
12+
// disconnect and move to left child
13+
14+
var prev = current.left!!
15+
while (prev.right != null) {
16+
prev = prev.right!!
17+
}
18+
19+
prev.right = current
20+
21+
val toVisit = current.left
22+
current.left = null
23+
current = toVisit
24+
} else {
25+
// count mode and traverse
26+
27+
if (current.`val` == currentVal) {
28+
++currentStreak
29+
} else {
30+
currentStreak = 1
31+
currentVal = current.`val`
32+
}
33+
34+
if (currentStreak > maxStreak) {
35+
maxStreak = currentStreak
36+
result.clear()
37+
result.add(currentVal)
38+
} else if (currentStreak == maxStreak) {
39+
result.add(currentVal)
40+
}
41+
42+
current = current.right
43+
}
44+
}
45+
46+
return result
1047
}
1148

1249
fun findMode(root: TreeNode?): IntArray {
13-
root.count()
14-
val max = counter.values.max()
15-
return counter
16-
.filter { (_, v) -> v == max }
17-
.keys
18-
.toIntArray()
50+
if (root == null)
51+
return IntArray(0)
52+
53+
return morris(root).toIntArray()
1954
}
2055
}

0 commit comments

Comments
 (0)