-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathunique_binary_search_trees_ii.rs
80 lines (74 loc) · 2.02 KB
/
unique_binary_search_trees_ii.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
///
/// Problem: Unique Binary Search Trees II
///
/// Given an integer `n`, return **all structurally unique BSTs** (binary search trees)
/// that store values from `1` to `n`.
///
/// **Example 1:**
/// ```plaintext
/// Input: n = 3
/// Output: [[1,null,2,null,3],[1,null,3,2],[2,1,3],[3,1,null,null,2],[3,2,null,1]]
/// Explanation: There are 5 unique BSTs.
/// ```
///
/// **Example 2:**
/// ```plaintext
/// Input: n = 1
/// Output: [[1]]
/// ```
///
/// **Constraints:**
/// - `1 <= n <= 8`
///
/// # Solution:
/// - **Time Complexity:** `O(C_n)` where `C_n` is the `n-th` Catalan number
/// - **Space Complexity:** `O(C_n)`
// 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 {
pub fn generate_trees(n: i32) -> Vec<Option<Rc<RefCell<TreeNode>>>> {
if n == 0 {
return Vec::new();
}
Self::generate_subtrees(1, n)
}
fn generate_subtrees(start: i32, end: i32) -> Vec<Option<Rc<RefCell<TreeNode>>>> {
if start > end {
return vec![None];
}
let mut all_trees = Vec::new();
for root_val in start..=end {
let left_subtrees = Self::generate_subtrees(start, root_val - 1);
let right_subtrees = Self::generate_subtrees(root_val + 1, end);
for left in &left_subtrees {
for right in &right_subtrees {
let root = Rc::new(RefCell::new(TreeNode {
val: root_val,
left: left.clone(),
right: right.clone(),
}));
all_trees.push(Some(root));
}
}
}
all_trees
}
}