95. Unique Binary Search Trees II

Given an integer n, return all the structurally unique BST's (binary search trees), which has exactly n nodes of unique values from 1 to n. Return the answer in any order.

 

Example 1:

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]]

Example 2:

Input: n = 1
Output: [[1]]

 

Constraints:

  • 1 <= n <= 8

Rust Solution

struct Solution;
use rustgym_util::*;

impl Solution {
    fn generate_trees(n: i32) -> Vec<TreeLink> {
        if n == 0 {
            return vec![];
        }
        Self::generate(1, n)
    }

    fn generate(left: i32, right: i32) -> Vec<TreeLink> {
        let mut res = vec![];
        if left > right {
            return vec![None];
        }
        if left == right {
            return vec![tree!(left)];
        }
        for middle in left..=right {
            for i in Self::generate(left, middle - 1) {
                for j in Self::generate(middle + 1, right) {
                    res.push(tree!(middle, i.clone(), j));
                }
            }
        }
        res
    }
}

#[test]
fn test() {
    let n = 3;
    let mut res = vec![
        tree!(1, None, tree!(3, tree!(2), None)),
        tree!(3, tree!(2, tree!(1), None), None),
        tree!(3, tree!(1, None, tree!(2)), None),
        tree!(2, tree!(1), tree!(3)),
        tree!(1, None, tree!(2, None, tree!(3))),
    ];
    let mut ans = Solution::generate_trees(n);
    ans.sort();
    res.sort();
    assert_eq!(ans, res);
}

Having problems with this solution? Click here to submit an issue on github.