mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
Merge pull request #99 from Joshua-Lu/patch-15
更新 0501.二叉搜索树中的众数 Java版本
This commit is contained in:
@ -344,46 +344,53 @@ public:
|
||||
|
||||
|
||||
Java:
|
||||
```java
|
||||
|
||||
```Java
|
||||
class Solution {
|
||||
private LinkedList<Integer> list = new LinkedList<>();
|
||||
private int currentValue;
|
||||
private int count;
|
||||
private int maxCount;
|
||||
ArrayList<Integer> resList;
|
||||
int maxCount;
|
||||
int count;
|
||||
TreeNode pre;
|
||||
|
||||
public int[] findMode(TreeNode root) {
|
||||
count = 0;
|
||||
resList = new ArrayList<>();
|
||||
maxCount = 0;
|
||||
currentValue = root.val;
|
||||
findModeTrl(root);
|
||||
int[] res = new int[list.size()];
|
||||
for (int i = 0; i < res.length; i++) {
|
||||
res[i] = list.get(i);
|
||||
count = 0;
|
||||
pre = null;
|
||||
findMode1(root);
|
||||
int[] res = new int[resList.size()];
|
||||
for (int i = 0; i < resList.size(); i++) {
|
||||
res[i] = resList.get(i);
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
private void findModeTrl (TreeNode root) {
|
||||
if (root == null) return;
|
||||
findModeTrl(root.left);
|
||||
if (root.val == currentValue) {
|
||||
count++;
|
||||
} else {
|
||||
currentValue = root.val;
|
||||
public void findMode1(TreeNode root) {
|
||||
if (root == null) {
|
||||
return;
|
||||
}
|
||||
findMode1(root.left);
|
||||
|
||||
int rootValue = root.val;
|
||||
// 计数
|
||||
if (pre == null || rootValue != pre.val) {
|
||||
count = 1;
|
||||
} else {
|
||||
count++;
|
||||
}
|
||||
|
||||
if (count == maxCount) {
|
||||
list.add(root.val);
|
||||
} else if (count > maxCount) {
|
||||
// 更新结果以及maxCount
|
||||
if (count > maxCount) {
|
||||
resList.clear();
|
||||
resList.add(rootValue);
|
||||
maxCount = count;
|
||||
list.clear();
|
||||
list.add(currentValue);
|
||||
} else if (count == maxCount) {
|
||||
resList.add(rootValue);
|
||||
}
|
||||
pre = root;
|
||||
|
||||
findModeTrl(root.right);
|
||||
findMode1(root.right);
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
Python:
|
||||
|
Reference in New Issue
Block a user