-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathall-possible-full-binary-trees.rs
61 lines (50 loc) · 1.41 KB
/
all-possible-full-binary-trees.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#![allow(dead_code, unused, unused_variables, non_snake_case)]
use std::cell::RefCell;
use std::rc::Rc;
// 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,
}
}
}
fn main() {}
struct Solution;
impl Solution {
/// 递归,n为偶数肯定不行
/// 假设左节点按1,3,5递增
/// 则右节点数为n-1-1,n-1-3,n-1-5
pub fn all_possible_fbt(n: i32) -> Vec<Option<Rc<RefCell<TreeNode>>>> {
let mut v = vec![];
if n % 2 == 0 {
return v;
}
if n == 1 {
v.push(Some(Rc::new(RefCell::new(TreeNode::new(0)))));
return v;
}
for i in (1..=n - 2).step_by(2) {
let left = Self::all_possible_fbt(i);
let right = Self::all_possible_fbt(n - i - 1);
for l in left.iter() {
for r in right.iter() {
let mut root = Rc::new(RefCell::new(TreeNode::new(0)));
root.borrow_mut().left = l.clone();
root.borrow_mut().right = r.clone();
v.push(Some(root))
}
}
}
v
}
}