[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
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<TreeNode *> generateSub(int N, int start){ if(N == 0){ // return vector<TreeNode *>(1, NULL); vector<TreeNode*> tmp; tmp.push_back(NULL); return tmp; } vector<TreeNode *> curLeft, curRight, result; for(int n = 1; n <= N; n++){ int rootval = n + start - 1; curLeft = generateSub(n-1, start); curRight = generateSub(N-n, rootval+1); for(int i = 0; i < curLeft.size(); i++){ for(int j = 0; j < curRight.size(); j++){ TreeNode *root = new TreeNode(rootval); root -> left = curLeft[i]; root -> right = curRight[j]; result.push_back(root); } } } return result; } vector<TreeNode *> generateTrees(int n) { // Start typing your C/C++ solution below // DO NOT write int main() function return generateSub(n, 1); } };
补充:软件开发 , C++ ,