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);
}
}