Unique Binary Search Trees,Unique Binary Search Trees II

Unique Binary Search Trees

Total Accepted: 69271 Total Submissions: 191174 Difficulty: Medium

Given n, how many structurally unique BST's (binary search trees) that store values 1...n?

For example,
Given n = 3, there are a total of 5 unique BST's.

   1         3     3      2      1
           /     /      /       
     3     2     1      1   3      2
    /     /                        
   2     1         2                 3
class Solution {
public:
    int numTrees(int n) {
        vector<int> map;
        map.push_back(1);
        for (int i = 1; i <= n; ++i) {
            int t = 0;
            for (int j = 0; j < i; ++j)
                t += map[j] * map[i-j-1];
            map.push_back(t);
        }
        return map.back();
    }
};

 

Unique Binary Search Trees II

Total Accepted: 45531 Total Submissions: 157430 Difficulty: Medium

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 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 start,int end){
        vector<TreeNode*> res;
        if(end < start) {
            res.push_back(NULL);
            return res;    
        }
        for(int rootValue = start; rootValue<=end; ++rootValue){
            vector<TreeNode*> left = generateTrees(start,rootValue-1);
            vector<TreeNode*> right = generateTrees(rootValue+1,end);
            for(int i=0;i<left.size();++i){
                for(int j=0;j<right.size();++j){
                    TreeNode *root = new TreeNode(rootValue);
                    root->left = left[i];
                    root->right = right[j];
                    res.push_back(root);
                }
            }
        }
        return res;
    }
    vector<TreeNode*> generateTrees(int n) {
        return n==0 ? vector<TreeNode*>():generateTrees(1,n);
    }
};
原文地址:https://www.cnblogs.com/zengzy/p/5055469.html