mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-09 15:59:06 +01:00
problems(rs): add “1161. Maximum Level Sum of a Binary Tree”
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
3df191c363
commit
c2480838e5
1 changed files with 60 additions and 0 deletions
60
problems/rs/maximum-level-sum-of-a-binary-tree.rs
Normal file
60
problems/rs/maximum-level-sum-of-a-binary-tree.rs
Normal file
|
@ -0,0 +1,60 @@
|
|||
// 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::cell::RefCell;
|
||||
use std::convert::TryInto;
|
||||
use std::rc::Rc;
|
||||
|
||||
impl Solution {
|
||||
fn max_sum(levels: &mut Vec<i32>, level: usize, root: Option<Rc<RefCell<TreeNode>>>) {
|
||||
if root == None {
|
||||
return;
|
||||
}
|
||||
|
||||
let r = root.unwrap();
|
||||
|
||||
if level >= levels.len() {
|
||||
levels.resize(level + 1, 0);
|
||||
}
|
||||
levels[level] += r.borrow().val;
|
||||
|
||||
Solution::max_sum(levels, level + 1, r.borrow().left.clone());
|
||||
Solution::max_sum(levels, level + 1, r.borrow().right.clone());
|
||||
}
|
||||
|
||||
pub fn max_level_sum(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
|
||||
let mut levels = vec![];
|
||||
|
||||
Solution::max_sum(&mut levels, 0, root);
|
||||
|
||||
levels
|
||||
.iter()
|
||||
.enumerate()
|
||||
.fold((0, i32::MIN), |(max_l, max_s), (l, s)| {
|
||||
if *s > max_s {
|
||||
(l + 1, *s)
|
||||
} else {
|
||||
(max_l, max_s)
|
||||
}
|
||||
})
|
||||
.0
|
||||
.try_into()
|
||||
.unwrap()
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue