LeetCode 965. Univalued Binary Tree

Problem Statement


use std::rc::Rc;
use std::cell::RefCell;
impl Solution {
fn dfs(root: Option<&Rc<RefCell<TreeNode>>>, val: i32) -> bool {
if let Some(n) = root {
if RefCell::borrow(&n).val != val {
return false;
}
return Self::dfs(RefCell::borrow(&n).left.as_ref(), val) &&
Self::dfs(RefCell::borrow(&n).right.as_ref(), val);
} else {
return true;
}
}
pub fn is_unival_tree(root: Option<Rc<RefCell<TreeNode>>>) -> bool {
if let Some(n) = root {
return Self::dfs(Some(&n), RefCell::borrow(&n).val);
} else {
return true;
}
}
}