File tree Expand file tree Collapse file tree 1 file changed +49
-14
lines changed
0501-find-mode-in-binary-search-tree Expand file tree Collapse file tree 1 file changed +49
-14
lines changed Original file line number Diff line number Diff line change 1
1
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
10
47
}
11
48
12
49
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()
19
54
}
20
55
}
You can’t perform that action at this time.
0 commit comments