mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-07 15:45:40 +08:00
update 0501.二叉搜索树中的众数: 修改 java,go 代码
This commit is contained in:
@ -54,7 +54,7 @@
|
||||
|
||||
1. 这个树都遍历了,用map统计频率
|
||||
|
||||
至于用前中后序那种遍历也不重要,因为就是要全遍历一遍,怎么个遍历法都行,层序遍历都没毛病!
|
||||
至于用前中后序哪种遍历也不重要,因为就是要全遍历一遍,怎么个遍历法都行,层序遍历都没毛病!
|
||||
|
||||
这里采用前序遍历,代码如下:
|
||||
|
||||
@ -354,7 +354,7 @@ public:
|
||||
|
||||
```java
|
||||
class Solution {
|
||||
public int[] findMode(FindModeInBinarySearchTree.TreeNode root) {
|
||||
public int[] findMode(TreeNode root) {
|
||||
Map<Integer, Integer> map = new HashMap<>();
|
||||
List<Integer> list = new ArrayList<>();
|
||||
if (root == null) return list.stream().mapToInt(Integer::intValue).toArray();
|
||||
@ -375,7 +375,7 @@ class Solution {
|
||||
return list.stream().mapToInt(Integer::intValue).toArray();
|
||||
}
|
||||
|
||||
void searchBST(FindModeInBinarySearchTree.TreeNode curr, Map<Integer, Integer> map) {
|
||||
void searchBST(TreeNode curr, Map<Integer, Integer> map) {
|
||||
if (curr == null) return;
|
||||
map.put(curr.val, map.getOrDefault(curr.val, 0) + 1);
|
||||
searchBST(curr.left, map);
|
||||
@ -556,46 +556,7 @@ class Solution:
|
||||
```
|
||||
## Go
|
||||
|
||||
暴力法(非BSL)
|
||||
|
||||
```go
|
||||
func findMode(root *TreeNode) []int {
|
||||
var history map[int]int
|
||||
var maxValue int
|
||||
var maxIndex int
|
||||
var result []int
|
||||
history=make(map[int]int)
|
||||
traversal(root,history)
|
||||
for k,value:=range history{
|
||||
if value>maxValue{
|
||||
maxValue=value
|
||||
maxIndex=k
|
||||
}
|
||||
}
|
||||
for k,value:=range history{
|
||||
if value==history[maxIndex]{
|
||||
result=append(result,k)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
func traversal(root *TreeNode,history map[int]int){
|
||||
if root.Left!=nil{
|
||||
traversal(root.Left,history)
|
||||
}
|
||||
if value,ok:=history[root.Val];ok{
|
||||
history[root.Val]=value+1
|
||||
}else{
|
||||
history[root.Val]=1
|
||||
}
|
||||
if root.Right!=nil{
|
||||
traversal(root.Right,history)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
计数法,不使用额外空间,利用二叉树性质,中序遍历
|
||||
|
||||
```go
|
||||
func findMode(root *TreeNode) []int {
|
||||
res := make([]int, 0)
|
||||
|
Reference in New Issue
Block a user