首页 > 其他 > 详细

[LeetCode] Unique Binary Search Trees II (难以忍受的递归)

时间:2014-08-07 00:16:37      阅读:356      评论:0      收藏:0      [点我收藏+]

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

 

class Solution {
private:
    vector<TreeNode*> generateTreesRec(int start, int end){
        vector<TreeNode*> v;
        if(start > end){
            v.push_back(NULL);
            return v;
        }
        for(int i = start; i <= end; ++i){
            vector<TreeNode*> left = generateTreesRec(start, i - 1);
            vector<TreeNode*> right = generateTreesRec(i + 1, end);
            TreeNode *node;
            for(int j = 0; j < left.size(); ++j){
                for(int k = 0; k < right.size(); ++k){
                    node = new TreeNode(i);
                    node->left = left[j];
                    node->right = right[k];
                    v.push_back(node);
                }
            }
        }
        return v;
    }
public:
    vector<TreeNode *> generateTrees(int n) {
        return generateTreesRec(1, n);
    }
};

 

[LeetCode] Unique Binary Search Trees II (难以忍受的递归),布布扣,bubuko.com

[LeetCode] Unique Binary Search Trees II (难以忍受的递归)

原文:http://www.cnblogs.com/Xylophone/p/3895850.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!