#236
Medium Algorithms Lowest common ancestor of a binary tree
Tree Depth-First Search Binary Tree
68.8% acceptance
Feb 27, 2026
18547
487
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
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>>> {
if root.is_none() {
return None;
}
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: i32, q: i32) -> Option<Rc<RefCell<TreeNode>>> {
if let Some(n) = node {
let n_borrow = n.borrow();
let val = n_borrow.val;
if val == p || val == q {
return Some(n.clone());
}
let left = Self::lca_helper(&n_borrow.left, p, q);
let right = Self::lca_helper(&n_borrow.right, p, q);
match (left, right) {
(Some(_), Some(_)) => Some(n.clone()),
(Some(l), None) => Some(l),
(None, Some(r)) => Some(r),
(None, None) => None,
}
} else {
None
}
}
}