From c47a82bc9a4b9da450415e65da9f4d1bdd140d11 Mon Sep 17 00:00:00 2001 From: Yuhao Ju Date: Sun, 4 Dec 2022 15:31:13 +0800 Subject: [PATCH] =?UTF-8?q?update=200501.=E4=BA=8C=E5=8F=89=E6=90=9C?= =?UTF-8?q?=E7=B4=A2=E6=A0=91=E4=B8=AD=E7=9A=84=E4=BC=97=E6=95=B0:=20?= =?UTF-8?q?=E4=BF=AE=E6=94=B9=20java=EF=BC=8Cgo=20=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0501.二叉搜索树中的众数.md | 45 ++------------------ 1 file changed, 3 insertions(+), 42 deletions(-) diff --git a/problems/0501.二叉搜索树中的众数.md b/problems/0501.二叉搜索树中的众数.md index 3c6362bf..f016ee58 100644 --- a/problems/0501.二叉搜索树中的众数.md +++ b/problems/0501.二叉搜索树中的众数.md @@ -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 map = new HashMap<>(); List 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 map) { + void searchBST(TreeNode curr, Map 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)