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
confused what "{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
OJ's Binary Tree Serialization:
The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.
Here's an example:
1 / \ 2 3 / 4 \ 5The above binary tree is serialized as
"{1,2,3,#,#,4,#,#,5}"
.代码:
1 vector<TreeNode *> generateTrees(int n, int start, int end){ 2 vector<TreeNode *> result; 3 result.clear(); 4 if(n == 0){ 5 result.push_back(NULL); 6 return result; 7 } 8 TreeNode *root; 9 for(int i = start; i <= end; i++){ 10 vector<TreeNode *> l = generateTrees(i-start, start, i-1); 11 vector<TreeNode *> r = generateTrees(end - i, i+1, end); 12 int m = l.size(), n = r.size(); 13 int j,k; 14 for(j = 0; j < m; j++){ 15 for(k = 0; k < n; k++){ 16 root = new TreeNode(i); 17 root->left = l[j]; 18 root->right = r[k]; 19 result.push_back(root); 20 } 21 } 22 } 23 return result; 24 } 25 vector<TreeNode *> generateTrees(int n) { 26 // IMPORTANT: Please reset any member data you declared, as 27 // the same Solution instance will be reused for each test case. 28 return generateTrees(n, 1, n); 29 }