95. 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*> helper(int st, int end){
        vector<TreeNode*>res;
        if(st>end){
            res.push_back(NULL);
            return res;
        }
        for(int i=st;i<=end;i++){
            vector<TreeNode*>lefts=helper(st,i-1);
            vector<TreeNode*>rights=helper(i+1,end);
            for(auto left: lefts){
                for(auto right: rights){
                    TreeNode* root = new TreeNode(i);
                    root->left = left;
                    root->right = right;
                    res.push_back(root);
                }
            }
        }
        return res;
    }
    vector<TreeNode*> generateTrees(int n) {
        if(!n)return vector<TreeNode*>(0);
        return helper(1,n);
    }
};

 

posted @ 2017-05-10 23:11  Tsunami_lj  阅读(101)  评论(0编辑  收藏  举报