LeetCode 637. Average of Levels in Binary Tree

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;

use std::collections::VecDeque;

impl Solution {
pub fn average_of_levels(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<f64> {
let mut ans = vec![];
if root.is_none() {
return ans;
}

let mut q = VecDeque::new();
q.push_back(root.clone());
while !q.is_empty() {
let size = q.len();
let mut sum : i64 = 0;
let mut i = size;
while i != 0 {
if let Some(node) = q.pop_front() {
sum += node.clone().unwrap().borrow().val as i64;
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);
}
i -= 1;
}
}
ans.push(sum as f64 / size as f64);
}
return ans;
}
}


LeetCode 654. Maximum Binary Tree

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 dfs(nums: &Vec<i32>, start: usize, end: usize) -> Option<Rc<RefCell<TreeNode>>> {
if start > end {
return None;
}
let (mut val, mut index) = (std::i32::MAX, 0);
for i in start..end + 1 {
if nums[i] > val {
val = nums[i];
index = i;
}
}

let mut node = TreeNode::new(val);
node.left = Self::dfs(nums, start, index - 1);
node.right = Self::dfs(nums, index + 1, end);
return Some(Rc::new(RefCell::new(node)));
}

pub fn construct_maximum_binary_tree(nums: Vec<i32>) -> Option<Rc<RefCell<TreeNode>>> {
return Self::dfs(&nums, 0, nums.len() - 1);
}
}