From 3e8bc12da207bed645bb283f9e5104be70bc553a Mon Sep 17 00:00:00 2001 From: Joshua <47053655+Joshua-Lu@users.noreply.github.com> Date: Fri, 14 May 2021 01:07:35 +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.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 0501.二叉搜索树中的众数 Java版本 --- problems/0501.二叉搜索树中的众数.md | 46 ++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/problems/0501.二叉搜索树中的众数.md b/problems/0501.二叉搜索树中的众数.md index 0e8c0d0e..0b2b1bb5 100644 --- a/problems/0501.二叉搜索树中的众数.md +++ b/problems/0501.二叉搜索树中的众数.md @@ -344,7 +344,53 @@ public: Java: +```Java +class Solution { + ArrayList 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: