From ce622d557e640b42e72aecff7cb137571bf70e41 Mon Sep 17 00:00:00 2001 From: fw_qaq <82551626+Jack-Zhang-1314@users.noreply.github.com> Date: Sun, 4 Dec 2022 00:01:46 +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 --- problems/0501.二叉搜索树中的众数.md | 38 ++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/problems/0501.二叉搜索树中的众数.md b/problems/0501.二叉搜索树中的众数.md index 7966e87c..a48fde34 100644 --- a/problems/0501.二叉搜索树中的众数.md +++ b/problems/0501.二叉搜索树中的众数.md @@ -925,6 +925,44 @@ impl Solution { } ``` +迭代: + +```rust +pub fn find_mode(root: Option>>) -> Vec { + let (mut cur, mut pre) = (root, i32::MIN); + let mut res = vec![]; + let mut stack = vec![]; + let (mut count, mut max_count) = (0, 0); + while !stack.is_empty() || cur.is_some() { + while let Some(node) = cur { + cur = node.borrow().left.clone(); + stack.push(node); + } + if let Some(node) = stack.pop() { + if pre == i32::MIN { + count = 1; + } else if pre == node.borrow().val { + count += 1; + } else { + count = 1; + } + match count.cmp(&max_count) { + std::cmp::Ordering::Equal => res.push(node.borrow().val), + std::cmp::Ordering::Greater => { + max_count = count; + res.clear(); + res.push(node.borrow().val); + } + _ => {} + } + pre = node.borrow().val; + cur = node.borrow().right.clone(); + } + } + res + } +``` +