[leetcode] Unique Binary Search Trees II


Unique Binary Search Trees II

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.

//递归
//对于n个node,每次取1~n之间的一个数i作为root节点,那么它的left child便是1~i-1的所有可能组合,right child就是i+1~n的所有可能组合。
//_generateTrees(int start, int end)便是求出[start, end)(不包括end,包括start)的所有可能的树的情形。
//时间复杂度不清楚,但肯定是有冗余的。因为很多计算是不需要的。
/**
 * 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) {
         return _generateTree(1, n + 1);
    }
    //[start, end)
    vector<TreeNode *> _generateTree(int start, int end){
        vector<TreeNode *> re;
        if(start >= end){
            re.push_back(NULL);
            return re;
        }
        else if(start + 1 == end){
            re.push_back(new TreeNode(start));
            return re;
        }
        else{
            for(int i = start; i < end; i++){
                vector<TreeNode*> left = _generateTree(start, i);
                vector<TreeNode*> right = _generateTree(i + 1, end);
                for(vector<TreeNode*>::iterator it1 = left.begin(); it1 != left.end(); it1++){
                    for(vector<TreeNode*>::iterator it2 = right.begin(); it2 != right.end(); it2++){
                        TreeNode * node = new TreeNode(i);
                        node->left = *it1;
                        node->right = *it2;
                        re.push_back(node);
                    }
                }
            }
            return re;
        }
    }
};

Untitled

 

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.