Unique Binary Search Trees II

Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1...n.

For example,
Given n = 3, your program should return all 5 unique BST's shown below.

   1         3     3      2      1
    \       /     /      / \      \
     3     2     1      1   3      2
    /     /       \                 \
   2     1         2                 3

递归的版本

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<TreeNode*> generateTrees(int n) {
        if(n < 1)   return {};
        return genTree(1, n);
    }

    vector<TreeNode *> genTree(int start, int end){
        vector<TreeNode *> ret;

        if(start > end){
            ret.push_back(NULL);
            return ret;
        }
        /*
        if(start == end){
            TreeNode *p = new TreeNode(start);
            ret.push_back(p);
            return ret;
        }*/

        for(int i = start; i <= end; i++){
            auto left = genTree(start, i - 1);
            auto right = genTree(i+1, end);

            for(auto lnode:left)
                for(auto rnode:right){
                    TreeNode *root = new TreeNode(i);
                    root->left = lnode;
                    root->right = rnode;
                    ret.push_back(root);
                }
        }

        return ret;
    }
};

results matching ""

    No results matching ""