|
| 1 | +/* |
| 2 | + * [0894] all-possible-full-binary-trees |
| 3 | + */ |
| 4 | + |
| 5 | +use super::utils::tree::*; |
| 6 | +struct Solution; |
| 7 | + |
| 8 | +use std::cell::RefCell; |
| 9 | +use std::collections::HashMap; |
| 10 | +use std::rc::Rc; |
| 11 | +impl Solution { |
| 12 | + pub fn all_possible_fbt(n: i32) -> Vec<Option<Rc<RefCell<TreeNode>>>> { |
| 13 | + let mut m: HashMap<i32, Vec<Option<Rc<RefCell<TreeNode>>>>> = HashMap::new(); |
| 14 | + Self::get(n, &mut m) |
| 15 | + } |
| 16 | + |
| 17 | + fn get( |
| 18 | + n: i32, |
| 19 | + m: &mut HashMap<i32, Vec<Option<Rc<RefCell<TreeNode>>>>>, |
| 20 | + ) -> Vec<Option<Rc<RefCell<TreeNode>>>> { |
| 21 | + if !m.contains_key(&n) { |
| 22 | + let mut ans = Vec::new(); |
| 23 | + if n == 1 { |
| 24 | + ans.push(Some(Rc::new(RefCell::new(TreeNode { |
| 25 | + left: Option::None, |
| 26 | + right: Option::None, |
| 27 | + val: 0, |
| 28 | + })))); |
| 29 | + } else if n % 2 == 1 { |
| 30 | + for x in 0..n { |
| 31 | + let y = n - 1 - x; |
| 32 | + for left in Self::all_possible_fbt(x) { |
| 33 | + for right in Self::all_possible_fbt(y) { |
| 34 | + let n = Some(Rc::new(RefCell::new(TreeNode { |
| 35 | + left: left.clone(), |
| 36 | + right: right.clone(), |
| 37 | + val: 0, |
| 38 | + }))); |
| 39 | + ans.push(n); |
| 40 | + } |
| 41 | + } |
| 42 | + } |
| 43 | + } |
| 44 | + m.insert(n, ans); |
| 45 | + } |
| 46 | + m.get(&n).unwrap().to_vec() |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +#[cfg(test)] |
| 51 | +mod tests { |
| 52 | + use super::*; |
| 53 | + |
| 54 | + #[test] |
| 55 | + fn test_case0() { |
| 56 | + assert_eq!(Solution::all_possible_fbt(1), vec![tree![0]]); |
| 57 | + assert_eq!( |
| 58 | + Solution::all_possible_fbt(7), |
| 59 | + vec![ |
| 60 | + tree![0, 0, 0, null, null, 0, 0, null, null, 0, 0], |
| 61 | + tree![0, 0, 0, null, null, 0, 0, 0, 0], |
| 62 | + tree![0, 0, 0, 0, 0, 0, 0], |
| 63 | + tree![0, 0, 0, 0, 0, null, null, null, null, 0, 0], |
| 64 | + tree![0, 0, 0, 0, 0, null, null, 0, 0] |
| 65 | + ] |
| 66 | + ); |
| 67 | + } |
| 68 | +} |
0 commit comments