From 5a1f18c31ece196465e6b6728ec244881a37f973 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Thu, 2 Nov 2023 15:10:03 +0100 Subject: [PATCH] =?UTF-8?q?problems(rs):=20add=20=E2=80=9C501.=20Find=20Mo?= =?UTF-8?q?de=20in=20Binary=20Search=20Tree=E2=80=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- .../rs/find-mode-in-binary-search-tree.rs | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 problems/rs/find-mode-in-binary-search-tree.rs diff --git a/problems/rs/find-mode-in-binary-search-tree.rs b/problems/rs/find-mode-in-binary-search-tree.rs new file mode 100644 index 0000000..ce530a6 --- /dev/null +++ b/problems/rs/find-mode-in-binary-search-tree.rs @@ -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>>, +// pub right: Option>>, +// } + +// 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>>) -> Vec { + let mut counters: BTreeMap = BTreeMap::new(); + + let mut stack: Vec>>> = 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() + } +}