码迷,mamicode.com
首页 > 其他好文 > 详细

95. Unique Binary Search Trees II

时间:2018-06-10 12:05:54      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:auto   binary   span   ++   ack   pre   i++   push   ini   

/**
 * 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

标签:auto   binary   span   ++   ack   pre   i++   push   ini   

原文地址:https://www.cnblogs.com/JTechRoad/p/9162149.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!