LeetCode 1120. Maximum Average Subtree

Problem Statement


use std::rc::Rc;
use std::cell::RefCell;
use std::borrow::Borrow;

impl Solution {
fn dfs(root: Option<&Rc<RefCell<TreeNode>>>, ans: &mut f64) -> (i32, i32) {
if let Some(node) = root {
let (l, r) = (Self::dfs(RefCell::borrow(&node).left.as_ref(), ans),
Self::dfs(RefCell::borrow(&node).right.as_ref(), ans));
let sum = l.0 + r.0 + RefCell::borrow(&node).val;
let total = 1 + l.1 + r.1;
let avg = sum as f64 / total as f64;
if avg > *ans {
*ans = avg;
}
return (sum, total);
} else {
return (0, 0);
}
}

pub fn maximum_average_subtree(root: Option<Rc<RefCell<TreeNode>>>) -> f64 {
let mut ans = 0.;
if root.is_none() {
return ans;
}
Self::dfs(Some(&root.unwrap()), &mut ans);
return ans;
}
}