mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-07 15:45:40 +08:00
Update 0501.二叉搜索树中的众数.md
This commit is contained in:
@ -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">
|
||||
|
Reference in New Issue
Block a user