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