首页 > 代码库 > 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; }};
递归真是个好东西!
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。