Update 0501.二叉搜索树中的众数.md

This commit is contained in:
fw_qaq
2022-12-04 00:01:46 +08:00
committed by GitHub
parent a6d407a44a
commit ce622d557e

View File

@ -925,6 +925,44 @@ impl Solution {
}
```
迭代:
```rust
pub fn find_mode(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<i32> {
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
}
```
<p align="center">
<a href="https://programmercarl.com/other/kstar.html" target="_blank">