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