|
| 1 | +/* |
| 2 | + * [0654] maximum-binary-tree |
| 3 | + */ |
| 4 | + |
| 5 | +use super::utils::tree::*; |
| 6 | +pub struct Solution {} |
| 7 | + |
| 8 | +// solution impl starts here |
| 9 | + |
| 10 | +// Definition for a binary tree node. |
| 11 | +// #[derive(Debug, PartialEq, Eq)] |
| 12 | +// pub struct TreeNode { |
| 13 | +// pub val: i32, |
| 14 | +// pub left: Option<Rc<RefCell<TreeNode>>>, |
| 15 | +// pub right: Option<Rc<RefCell<TreeNode>>>, |
| 16 | +// } |
| 17 | +// |
| 18 | +// impl TreeNode { |
| 19 | +// #[inline] |
| 20 | +// pub fn new(val: i32) -> Self { |
| 21 | +// TreeNode { |
| 22 | +// val, |
| 23 | +// left: None, |
| 24 | +// right: None |
| 25 | +// } |
| 26 | +// } |
| 27 | +// } |
| 28 | +use std::cell::RefCell; |
| 29 | +use std::rc::Rc; |
| 30 | +impl Solution { |
| 31 | + pub fn construct_maximum_binary_tree(nums: Vec<i32>) -> Option<Rc<RefCell<TreeNode>>> { |
| 32 | + if nums.len() == 0 { |
| 33 | + return Option::None; |
| 34 | + } |
| 35 | + |
| 36 | + let mut i = 0; |
| 37 | + for j in 0..nums.len() { |
| 38 | + if nums[j] > nums[i] { |
| 39 | + i = j; |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + let left = Self::construct_maximum_binary_tree(nums[..i].to_vec()); |
| 44 | + let right = Self::construct_maximum_binary_tree(nums[i + 1..].to_vec()); |
| 45 | + |
| 46 | + Some(Rc::new(RefCell::new(TreeNode { |
| 47 | + val: nums[i], |
| 48 | + left: left, |
| 49 | + right: right, |
| 50 | + }))) |
| 51 | + } |
| 52 | +} |
| 53 | +// solution impl ends here |
| 54 | + |
| 55 | +// solution tests starts here |
| 56 | + |
| 57 | +#[cfg(test)] |
| 58 | +mod tests { |
| 59 | + use super::*; |
| 60 | + |
| 61 | + #[test] |
| 62 | + fn test_case0() { |
| 63 | + assert_eq!( |
| 64 | + Solution::construct_maximum_binary_tree(vec![3, 2, 1, 6, 0, 5]), |
| 65 | + tree![6, 3, 5, null, 2, 0, null, null, 1] |
| 66 | + ); |
| 67 | + } |
| 68 | +} |
| 69 | + |
| 70 | +// solution tests ends here |
0 commit comments