lintcode-不同的二叉查找树II

给出n,生成所有由1…n为节点组成的不同的二叉查找树

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */
class Solution {
public:
    /**
     * @paramn n: An integer
     * @return: A list of root
     */
     
    vector<TreeNode *> createTrees(int start, int end) {
        
        vector<TreeNode *> ret;
        
        if(start > end) {
            ret.push_back((TreeNode *)NULL);
            return ret;
        } 
        
        if(start == end) {
            TreeNode * node = new TreeNode(start);
            ret.push_back(node);
            return ret;
        }
        
        for(int i = start; i <= end; ++i) {
            vector<TreeNode *> left = createTrees(start, i-1);
            vector<TreeNode *> right = createTrees(i+1, end);
            
            for(auto lnode : left) {
                for(auto rnode : right) {
                    TreeNode * root = new TreeNode(i);
                    root->left = lnode;
                    root->right = rnode;
                    ret.push_back(root);   
                }
             }
        }
        
        return ret;
    }
     
    vector<TreeNode *> generateTrees(int n) {
        // write your code here
        
        return createTrees(1, n);
    }
};
    原文作者:鬼谷神奇
    原文地址: https://www.jianshu.com/p/c14c25cabda4#comments
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞