1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-11-14 01:49:41 +01:00
LeetCode/problems/rs/find-mode-in-binary-search-tree.rs
2023-11-02 15:10:54 +01:00

54 lines
1.4 KiB
Rust

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()
}
}