Skip to content

Commit 76b0537

Browse files
authored
Update Find Mode in Binary Search Tree.java
1 parent 7b6bf88 commit 76b0537

File tree

1 file changed

+46
-37
lines changed

1 file changed

+46
-37
lines changed

Easy/Find Mode in Binary Search Tree.java

Lines changed: 46 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -14,44 +14,53 @@
1414
* }
1515
*/
1616
class Solution {
17-
Integer prev = null;
18-
int count = 1;
19-
int max = 0;
20-
public int[] findMode(TreeNode root) {
21-
if (root == null) {
22-
return new int[0];
17+
public int[] findMode(TreeNode root) {
18+
ResultWrapper resultWrapper = new ResultWrapper();
19+
inorder(root, resultWrapper);
20+
return resultWrapper.result.stream().mapToInt(Integer::intValue).toArray();
2321
}
24-
List<Integer> list = new ArrayList<>();
25-
traverse(root, list);
26-
int[] ans = new int[list.size()];
27-
for (int i = 0; i < list.size(); i++) {
28-
ans[i] = list.get(i);
22+
23+
private void inorder(TreeNode node, ResultWrapper resultWrapper) {
24+
if (node == null) {
25+
return;
26+
}
27+
inorder(node.left, resultWrapper);
28+
int val = node.val;
29+
resultWrapper.recordStreak(val);
30+
resultWrapper.updateResult(val);
31+
inorder(node.right, resultWrapper);
2932
}
30-
return ans;
31-
}
32-
33-
private void traverse(TreeNode root, List<Integer> list) {
34-
if (root == null) {
35-
return;
33+
34+
private static class ResultWrapper {
35+
private int maxStreak;
36+
private int currStreak;
37+
private Integer curr;
38+
private List<Integer> result;
39+
40+
public ResultWrapper() {
41+
this.maxStreak = 0;
42+
this.currStreak = 0;
43+
this.curr = 0;
44+
this.result = new ArrayList<>();
45+
}
46+
47+
public void recordStreak(int num) {
48+
if (num == curr) {
49+
currStreak++;
50+
} else {
51+
currStreak = 1;
52+
curr = num;
53+
}
54+
}
55+
56+
public void updateResult(int num) {
57+
if (currStreak > maxStreak) {
58+
result.clear();
59+
maxStreak = currStreak;
60+
}
61+
if (currStreak == maxStreak) {
62+
result.add(num);
63+
}
64+
}
3665
}
37-
traverse(root.left, list);
38-
if (prev != null) {
39-
if (root.val == prev) {
40-
count++;
41-
}
42-
else {
43-
count = 1;
44-
}
45-
}
46-
if (count > max) {
47-
max = count;
48-
list.clear();
49-
list.add(root.val);
50-
}
51-
else if (count == max) {
52-
list.add(root.val);
53-
}
54-
prev = root.val;
55-
traverse(root.right, list);
56-
}
5766
}

0 commit comments

Comments
 (0)