给定n求二叉搜索树的个数

Given 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

 

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

 

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
private:
    vector generate(int l, int r)
    {
        vector ans; 
        if (l > r)
        {
            ans.push_back(NULL);
        }
        else
        {
            for (int i=l; i<=r; i++){
                vector left = generate(l, i-1);
                vector right = generate(i+1, r);
                for (int j=0; j)
                {
                   for (int k=0; k)
                    {
                        TreeNode *pRoot = new TreeNode(i);
                        pRoot->left = left[j];
                        pRoot->right = right[k];
                        ans.push_back(pRoot);
                    }
                }

            }
            
        }
        
        return ans;
    }
public:
    vector generateTrees(int n) {
        return generate(1, n);
    }
};

 

转载于:https://www.cnblogs.com/zhhwgis/p/3956628.html

你可能感兴趣的:(给定n求二叉搜索树的个数)