235. Lowest Common Ancestor of a Binary Search Tree
Given a binary search tree (BST), find the lowest common ancestor (LCA) 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).”
Example 1:

Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8 Output: 6 Explanation: The LCA of nodes 2 and 8 is 6.
Example 2:

Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4 Output: 2 Explanation: The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.
Example 3:
Input: root = [2,1], p = 2, q = 1 Output: 2
Constraints:
- The number of nodes in the tree is in the range
[2, 105]
. -109 <= Node.val <= 109
- All
Node.val
are unique. p != q
p
andq
will exist in the BST.
Rust Solution
struct Solution;
use rustgym_util::*;
impl Solution {
fn lowest_common_ancestor(mut root: TreeLink, p: TreeLink, q: TreeLink) -> TreeLink {
let p_val = p.unwrap().borrow().val;
let q_val = q.unwrap().borrow().val;
while let Some(node) = root.clone() {
let mut node = node.borrow_mut();
let val = node.val;
if val > p_val && val > q_val {
root = node.left.take();
continue;
}
if val < p_val && val < q_val {
root = node.right.take();
continue;
}
node.left.take();
node.right.take();
break;
}
root
}
}
#[test]
fn test() {
let root = tree!(
6,
tree!(2, tree!(0), tree!(4, tree!(3), tree!(5))),
tree!(8, tree!(7), tree!(9))
);
let p = tree!(2);
let q = tree!(8);
let res = tree!(6);
assert_eq!(Solution::lowest_common_ancestor(root, p, q), res);
let root = tree!(
6,
tree!(2, tree!(0), tree!(4, tree!(3), tree!(5))),
tree!(8, tree!(7), tree!(9))
);
let p = tree!(2);
let q = tree!(4);
let res = tree!(2);
assert_eq!(Solution::lowest_common_ancestor(root, p, q), res);
let root = tree!(2, tree!(1), None);
let p = tree!(2);
let q = tree!(1);
let res = tree!(2);
assert_eq!(Solution::lowest_common_ancestor(root, p, q), res);
}
Having problems with this solution? Click here to submit an issue on github.