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

LeetCode Unique Binary Search Trees II

class Solution {private:    vector<TreeNode *> res;public:    vector<TreeNode *> generateTrees(int n) {        res.clear();        res = dfs(1, n + 1);        return res;    }    vector<TreeNode*> dfs(int start, int end) {        vector<TreeNode*> res;        if (start >= end) {            res.push_back(NULL);            return res;        }        TreeNode* rt = NULL;        for (int i=start; i<end; i++) {            vector<TreeNode*> lsub = dfs(start, i);            vector<TreeNode*> rsub = dfs(i+1, end);            for (int li=0; li<lsub.size(); li++) {                for (int ri=0; ri<rsub.size(); ri++) {                    rt = new TreeNode(i);                    rt->left = lsub[li];                    rt->right= rsub[ri];                    res.push_back(rt);                }            }        }        return res;    }};

递归真是个好东西!