mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 08:50:15 +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
|
|
||||||
|
```Java
|
||||||
class Solution {
|
class Solution {
|
||||||
private LinkedList<Integer> list = new LinkedList<>();
|
ArrayList<Integer> resList;
|
||||||
private int currentValue;
|
int maxCount;
|
||||||
private int count;
|
int count;
|
||||||
private int maxCount;
|
TreeNode pre;
|
||||||
|
|
||||||
public int[] findMode(TreeNode root) {
|
public int[] findMode(TreeNode root) {
|
||||||
count = 0;
|
resList = new ArrayList<>();
|
||||||
maxCount = 0;
|
maxCount = 0;
|
||||||
currentValue = root.val;
|
count = 0;
|
||||||
findModeTrl(root);
|
pre = null;
|
||||||
int[] res = new int[list.size()];
|
findMode1(root);
|
||||||
for (int i = 0; i < res.length; i++) {
|
int[] res = new int[resList.size()];
|
||||||
res[i] = list.get(i);
|
for (int i = 0; i < resList.size(); i++) {
|
||||||
|
res[i] = resList.get(i);
|
||||||
}
|
}
|
||||||
return res;
|
return res;
|
||||||
}
|
}
|
||||||
|
|
||||||
private void findModeTrl (TreeNode root) {
|
public void findMode1(TreeNode root) {
|
||||||
if (root == null) return;
|
if (root == null) {
|
||||||
findModeTrl(root.left);
|
return;
|
||||||
if (root.val == currentValue) {
|
}
|
||||||
count++;
|
findMode1(root.left);
|
||||||
} else {
|
|
||||||
currentValue = root.val;
|
int rootValue = root.val;
|
||||||
|
// 计数
|
||||||
|
if (pre == null || rootValue != pre.val) {
|
||||||
count = 1;
|
count = 1;
|
||||||
|
} else {
|
||||||
|
count++;
|
||||||
}
|
}
|
||||||
|
// 更新结果以及maxCount
|
||||||
if (count == maxCount) {
|
if (count > maxCount) {
|
||||||
list.add(root.val);
|
resList.clear();
|
||||||
} else if (count > maxCount) {
|
resList.add(rootValue);
|
||||||
maxCount = count;
|
maxCount = count;
|
||||||
list.clear();
|
} else if (count == maxCount) {
|
||||||
list.add(currentValue);
|
resList.add(rootValue);
|
||||||
}
|
}
|
||||||
|
pre = root;
|
||||||
|
|
||||||
findModeTrl(root.right);
|
findMode1(root.right);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Python:
|
Python:
|
||||||
|
Reference in New Issue
Block a user