From 92980de383398d6540a48dcf648996df00726408 Mon Sep 17 00:00:00 2001 From: ironartisan <54694467+ironartisan@users.noreply.github.com> Date: Tue, 7 Sep 2021 11:28:50 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A00501.=E4=BA=8C=E5=8F=89?= =?UTF-8?q?=E6=90=9C=E7=B4=A2=E6=A0=91=E4=B8=AD=E7=9A=84=E4=BC=97=E6=95=B0?= =?UTF-8?q?.md=E8=BF=AD=E4=BB=A3Java=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0501.二叉搜索树中的众数.md | 38 ++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/problems/0501.二叉搜索树中的众数.md b/problems/0501.二叉搜索树中的众数.md index aeddc600..22d4f4ac 100644 --- a/problems/0501.二叉搜索树中的众数.md +++ b/problems/0501.二叉搜索树中的众数.md @@ -429,6 +429,44 @@ class Solution { } } ``` +迭代法 +```java +class Solution { + public int[] findMode(TreeNode root) { + TreeNode pre = null; + Stack stack = new Stack<>(); + List result = new ArrayList<>(); + int maxCount = 0; + int count = 0; + TreeNode cur = root; + while (cur != null || !stack.isEmpty()) { + if (cur != null) { + stack.push(cur); + cur =cur.left; + }else { + cur = stack.pop(); + // 计数 + if (pre == null || cur.val != pre.val) { + count = 1; + }else { + count++; + } + // 更新结果 + if (count > maxCount) { + maxCount = count; + result.clear(); + result.add(cur.val); + }else if (count == maxCount) { + result.add(cur.val); + } + pre = cur; + cur = cur.right; + } + } + return result.stream().mapToInt(Integer::intValue).toArray(); + } +} +``` ## Python