mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-14 15:00:42 +08:00
Update 0501.二叉搜索树中的众数.md
This commit is contained in:
@ -876,6 +876,55 @@ object Solution {
|
||||
}
|
||||
```
|
||||
|
||||
## rust
|
||||
|
||||
递归:
|
||||
|
||||
```rust
|
||||
impl Solution {
|
||||
pub fn find_mode(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<i32> {
|
||||
let mut count = 0;
|
||||
let mut max_count = 0;
|
||||
let mut res = vec![];
|
||||
let mut pre = i32::MIN;
|
||||
Self::search_bst(&root, &mut pre, &mut res, &mut count, &mut max_count);
|
||||
res
|
||||
}
|
||||
pub fn search_bst(
|
||||
cur: &Option<Rc<RefCell<TreeNode>>>,
|
||||
mut pre: &mut i32,
|
||||
res: &mut Vec<i32>,
|
||||
count: &mut i32,
|
||||
max_count: &mut i32,
|
||||
) {
|
||||
if cur.is_none() {
|
||||
return;
|
||||
}
|
||||
|
||||
let cur_node = cur.as_ref().unwrap().borrow();
|
||||
Self::search_bst(&cur_node.left, pre, res, count, max_count);
|
||||
if *pre == i32::MIN {
|
||||
*count = 1;
|
||||
} else if *pre == cur_node.val {
|
||||
*count += 1;
|
||||
} else {
|
||||
*count = 1;
|
||||
};
|
||||
match count.cmp(&max_count) {
|
||||
std::cmp::Ordering::Equal => res.push(cur_node.val),
|
||||
std::cmp::Ordering::Greater => {
|
||||
*max_count = *count;
|
||||
res.clear();
|
||||
res.push(cur_node.val);
|
||||
}
|
||||
_ => {}
|
||||
};
|
||||
*pre = cur_node.val;
|
||||
Self::search_bst(&cur_node.right, pre, res, count, max_count);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
<p align="center">
|
||||
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
||||
|
Reference in New Issue
Block a user