#235
Medium Algorithms Lowest common ancestor of a binary search tree
Tree Depth-First Search Binary Search Tree Binary Tree
70.1% acceptance
Feb 27, 2026
12212
358
Given a binary search tree (BST), find the lowest common ancestor (LCA) node of two given nodes in the BST.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”
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 lowest_common_ancestor(root: Option<Rc<RefCell<TreeNode>>>, p: Option<Rc<RefCell<TreeNode>>>, q: Option<Rc<RefCell<TreeNode>>>) -> Option<Rc<RefCell<TreeNode>>> {
let p_val = p.as_ref().unwrap().borrow().val;
let q_val = q.as_ref().unwrap().borrow().val;
Self::lca_helper(&root, p_val, q_val)
}
fn lca_helper(node: &Option<Rc<RefCell<TreeNode>>>, p_val: i32, q_val: i32) -> Option<Rc<RefCell<TreeNode>>> {
if let Some(n) = node {
let val = n.borrow().val;
if p_val < val && q_val < val {
Self::lca_helper(&n.borrow().left, p_val, q_val)
} else if p_val > val && q_val > val {
Self::lca_helper(&n.borrow().right, p_val, q_val)
} else {
Some(n.clone())
}
} else {
None
}
}
}