diff --git a/problems/0501.二叉搜索树中的众数.md b/problems/0501.二叉搜索树中的众数.md index 3c6362bf..7966e87c 100644 --- a/problems/0501.二叉搜索树中的众数.md +++ b/problems/0501.二叉搜索树中的众数.md @@ -876,6 +876,55 @@ object Solution { } ``` +## rust + +递归: + +```rust +impl Solution { + pub fn find_mode(root: Option>>) -> Vec { + 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>>, + mut pre: &mut i32, + res: &mut Vec, + 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); + } +} +``` +