finding unique bsts

Solutions on MaxInterview for finding unique bsts by the best coders in the world

showing results for - "finding unique bsts"
Karl
01 Jun 2016
1#define vN vector<Node *>
2
3class Node{
4public:
5    long val = 0;
6    Node *left = nullptr, *right = nullptr;
7    Node(int val_): val(val_){}
8};
9
10vN find_unique_BSTs(long start, long end){
11    vN res = {};
12
13    if(start > end){
14        res.push_back(nullptr);
15        return res;
16    }
17
18    for(long i = start; i <= end; ++i){
19        vN left = find_unique_BSTs(start, i-1);
20        vN right = find_unique_BSTs(i+1, end);
21        for(Node *l: left){
22            for(Node *r: right){
23                Node *root = new Node(i);
24                root->left = l;
25                root->right = r;
26                res.push_back(root);
27            }
28        }
29    }
30    return res;
31}
32
33vN res = find_unique_BSTs(1,n);