[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
由于要列出所有解,所有就只能用DFS枚举了。
1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 vector<TreeNode *> generate(int beg, int end) 13 { 14 vector<TreeNode* > ret; 15 if (beg > end) 16 { 17 ret.push_back(NULL); 18 return ret; 19 } 20 21 for(int i = beg; i <= end; i++) 22 { 23 vector<TreeNode* > leftTree = generate(beg, i - 1); 24 vector<TreeNode* > rightTree = generate(i + 1, end); 25 for(int j = 0; j < leftTree.size(); j++) 26 for(int k = 0; k < rightTree.size(); k++) 27 { 28 TreeNode *node = new TreeNode(i + 1); 29 ret.push_back(node); 30 node->left = leftTree[j]; 31 node->right = rightTree[k]; 32 } 33 } 34 35 return ret; 36 } 37 38 vector<TreeNode *> generateTrees(int n) { 39 // Start typing your C/C++ solution below 40 // DO NOT write int main() function 41 return generate(0, n - 1); 42 } 43 };