LeetCode 865. Smallest Subtree with all the Deepest Nodes

Problem Statement


// 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 {
fn get_max_depth(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
if let Some(node) = root {
return std::cmp::max(Self::get_max_depth(RefCell::borrow(&node).left.clone()),
Self::get_max_depth(RefCell::borrow(&node).right.clone())) + 1;
} else {
return 0;
}
}

pub fn subtree_with_all_deepest(root: Option<Rc<RefCell<TreeNode>>>) -> Option<Rc<RefCell<TreeNode>>> {
if let Some(node) = root {
let diff = Self::get_max_depth(RefCell::borrow(&node).left.clone()) -
Self::get_max_depth(RefCell::borrow(&node).right.clone());
if diff == 0 {
return Some(node);
} else if diff > 0 {
return Self::subtree_with_all_deepest(RefCell::borrow(&node).left.clone());
} else {
return Self::subtree_with_all_deepest(RefCell::borrow(&node).right.clone());
}
} else {
return root;
}
}
}