problems(rs): add “501. Find Mode in Binary Search Tree”

Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
Matej Focko 2023-11-02 15:10:03 +01:00
parent 0d50e8082a
commit 5a1f18c31e
Signed by: mfocko
GPG key ID: 7C47D46246790496

View file

@ -0,0 +1,54 @@
use std::cell::RefCell;
use std::collections::BTreeMap;
use std::rc::Rc;
// Definition for a binary tree node.
// #[derive(Debug, PartialEq, Eq)]
// pub struct TreeNode {
// pub val: i32,
// pub left: Option<Rc<RefCell<TreeNode>>>,
// pub right: Option<Rc<RefCell<TreeNode>>>,
// }
// impl TreeNode {
// #[inline]
// pub fn new(val: i32) -> Self {
// TreeNode {
// val,
// left: None,
// right: None,
// }
// }
// }
// struct Solution {}
impl Solution {
pub fn find_mode(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<i32> {
let mut counters: BTreeMap<i32, usize> = BTreeMap::new();
let mut stack: Vec<Option<Rc<RefCell<TreeNode>>>> = Vec::new();
stack.push(root.clone());
while let Some(node) = stack.pop() {
if node.is_none() {
continue;
}
let node = node.unwrap();
let n = node.borrow();
counters
.entry(n.val)
.and_modify(|curr| *curr += 1)
.or_insert(1);
stack.push(n.left.clone());
stack.push(n.right.clone());
}
let maximum = *counters.values().max().unwrap();
counters
.iter()
.filter_map(|(&k, &c)| if c == maximum { Some(k) } else { None })
.collect()
}
}