forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
45 lines (43 loc) · 1.05 KB
/
Solution.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int max = 0;
int cur = 0;
TreeNode preNode = null;
public int[] findMode(TreeNode root) {
ArrayList<Integer> list = new ArrayList<>();
findMode(root, list);
int[] res = new int[list.size()];
for (int i = 0; i < list.size(); i++) {
res[i] = list.get(i);
}
return res;
}
private void findMode(TreeNode root, ArrayList<Integer> list) {
if (root == null) {
return;
}
findMode(root.left, list);
if (preNode != null && root.val == preNode.val) {
cur++;
} else {
cur = 1;
}
if (max < cur) {
max = cur;
list.clear();
list.add(root.val);
} else if (max == cur) {
list.add(root.val);
}
preNode = root;
findMode(root.right, list);
}
}