Unique Binary Search Trees II [Leetcode 解题报告]

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

思路:分别将每个点作为根节点,分配左右子树的节点数,然后归并在一起就行了,代码如下:

vector<TreeNode*> createTrees(int start,int end){
        vector<TreeNode*> results;
        if(start>end){
            results.push_back(NULL);
        }
        for(int i=start;i<=end;i++){
            vector<TreeNode*> left=createTrees(start,i-1);
            vector<TreeNode*> right=createTrees(i+1,end);
            for(int j=0;j<left.size();j++){
                for(int k=0;k<right.size();k++){
                    TreeNode *p=new TreeNode(i);
                    p->left=left[j];
                    p->right=right[k];
                    results.push_back(p);
                }
            }
        }
        return results;
    }
    vector<TreeNode*> generateTrees(int n) {
        vector<TreeNode*> result;
        if(n<1)return result;
        return createTrees(1,n);
    }

你可能感兴趣的:(LeetCode)