95. Unique Binary Search Trees II

Posted jtechroad

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了95. 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) {
        vector<TreeNode*> res;
        helper(res, 1, n);
        return res;
    }
    void helper(vector<TreeNode*>& res, int _min, int _max) {
        if (_min > _max)    return;
        for (int i = _min; i <= _max; i++) {
            vector<TreeNode*> left, right;
            helper(left, _min, i-1);
            helper(right, i+1, _max);
            if (left.size() == 0)   left.push_back(NULL);
            if (right.size() == 0)  right.push_back(NULL);
            for (auto l : left)
                for (auto r : right) {
                    TreeNode* root = new TreeNode(i);
                    root->left = l;
                    root->right = r;
                    res.push_back(root);
                }
        }
    }
};

 

以上是关于95. Unique Binary Search Trees II的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 95. Unique Binary Search Trees II

Leetcode 95. Unique Binary Search Trees II

LeetCode 95. Unique Binary Search Trees II

95. Unique Binary Search Trees II

95. Unique Binary Search Trees II

[leetcode-95-Unique Binary Search Trees II]