首页 > 代码库 > Unique Binary Search Trees II

Unique Binary Search Trees II

方法:这里使用递归的方式

/**
 * 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) {
        if(n == 0)
            return vector<TreeNode *>();
        return generate(0, n-1);
    }
    
    vector<TreeNode *> generate(int begin, int end)
    {
        vector<TreeNode *> result;
        if(begin > end)
        {
            result.push_back(nullptr);
            return result;
        }
        
        for(int i=begin; i<=end; ++i)
        {
            vector<TreeNode *>left = generate(begin, i-1);
            vector<TreeNode *>right = generate(i+1, end);
            
            for(int j=0; j<left.size(); ++j)
            {
                for(int k=0; k<right.size(); ++k)
                {
                    TreeNode *tmp = new TreeNode(i+1);
                    result.push_back(tmp);
                    tmp->left = left[j];
                    tmp->right = right[k];
                }
            }
        }
        
        return result;
    }
};

 

Unique Binary Search Trees II