mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 19:44:45 +08:00
Update 0501.二叉搜索树中的众数.md
添加 0501.二叉搜索树中的众数 Java版本
This commit is contained in:
@ -344,7 +344,53 @@ public:
|
|||||||
|
|
||||||
|
|
||||||
Java:
|
Java:
|
||||||
|
```Java
|
||||||
|
class Solution {
|
||||||
|
ArrayList<Integer> resList;
|
||||||
|
int maxCount;
|
||||||
|
int count;
|
||||||
|
TreeNode pre;
|
||||||
|
|
||||||
|
public int[] findMode(TreeNode root) {
|
||||||
|
resList = new ArrayList<>();
|
||||||
|
maxCount = 0;
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
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++;
|
||||||
|
}
|
||||||
|
// 更新结果以及maxCount
|
||||||
|
if (count > maxCount) {
|
||||||
|
resList.clear();
|
||||||
|
resList.add(rootValue);
|
||||||
|
maxCount = count;
|
||||||
|
} else if (count == maxCount) {
|
||||||
|
resList.add(rootValue);
|
||||||
|
}
|
||||||
|
pre = root;
|
||||||
|
|
||||||
|
findMode1(root.right);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
Python:
|
Python:
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user