LeetCode 1161. Maximum Level Sum of a Binary Tree

Problem Statement


use std::rc::Rc;
use std::cell::RefCell;
use std::collections::VecDeque;

impl Solution {
pub fn max_level_sum(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
let (mut ans, mut sum, mut level) = (0, std::i32::MIN, 1);
if root.is_none() {
return ans;
}

let mut q = VecDeque::new();
q.push_back(root.clone());

while !q.is_empty() {
let (mut size, mut cur_sum) = (q.len(), 0);
while size != 0 {
if let Some(node) = q.pop_front() {
cur_sum += node.clone().unwrap().borrow().val;
let (left, right) = (
node.clone().unwrap().borrow().left.clone(),
node.clone().unwrap().borrow().right.clone()
);
if !left.is_none() {
q.push_back(left);
}
if !right.is_none() {
q.push_back(right);
}
}
size -= 1;
}
if cur_sum > sum {
sum = cur_sum;
ans = level;
}
level += 1;
}
return ans;
}
}