#501
Easy Algorithms Find mode in binary search tree
Tree Depth-First Search Binary Search Tree Binary Tree
58.5% acceptance
Feb 19, 2026
4104
814
Given the root of a binary search tree (BST) with duplicates, return all the mode(s) (i.e., the most frequently occurred element) in it.
If the tree has more than one mode, return them in any order.
Assume a BST is defined as follows:
The left subtree of a node contains only nodes with keys less than or equal to the node's key.
The right subtree of a node contains only nodes with keys greater than or equal to the node's key.
Both the left and right subtrees must also be binary search trees.
Solution
Rust
Time O(n)
Space O(n)
// 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
// }
// }
// }
use std::rc::Rc;
use std::cell::RefCell;
impl Solution {
pub fn find_mode(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<i32> {
let mut result: Vec<i32> = Vec::new();
let mut max_count = 0i32;
let mut current_count = 0i32;
let mut current_val = i32::MIN;
fn inorder(
node: &Option<Rc<RefCell<TreeNode>>>,
cv: &mut i32,
cc: &mut i32,
mc: &mut i32,
res: &mut Vec<i32>,
) {
if let Some(n) = node {
let nb = n.borrow();
inorder(&nb.left, cv, cc, mc, res);
let val = nb.val;
if val == *cv {
*cc += 1;
} else {
*cv = val;
*cc = 1;
}
if *cc > *mc {
*mc = *cc;
res.clear();
res.push(val);
} else if *cc == *mc {
res.push(val);
}
inorder(&nb.right, cv, cc, mc, res);
}
}
inorder(&root, &mut current_val, &mut current_count, &mut max_count, &mut result);
result
}
}