LeetCode 1123 Lowest Common Ancestor of Deepest Leaves

Problem Statement


use std::rc::Rc;
use std::cell::RefCell;
use std::cmp::max;

impl Solution {
pub fn compute_depth(node : Option<&Rc<RefCell<TreeNode>>>) -> u32 {
if let Some(n) = node {
return 1 + max(Solution::compute_depth(n.borrow().left.as_ref()),
Solution::compute_depth(n.borrow().right.as_ref()));
} else {
return 0;
}
}

pub fn lca_deepest_leaves(root: Option<Rc<RefCell<TreeNode>>>) -> Option<Rc<RefCell<TreeNode>>> {
if let Some(node) = root.clone() {
let (l, r) = (Solution::compute_depth(node.borrow().left.as_ref()),
Solution::compute_depth(node.borrow().right.as_ref()));
if l == r {
return Some(node);
} else if l < r {
return Solution::lca_deepest_leaves(node.borrow().right.clone());
} else {
return Solution::lca_deepest_leaves(node.borrow().left.clone());
}
} else {
return None;
}
}
}