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
Solution: 1. DFS directly. (from the Internet)
2. DP + DFS. (my solution)
a. Generate trees for 'n' from 1 to n. (DP)
b. When generate trees for n = i, get the left and right subtrees
by copying tree structures of dp[1...i-1]. (copy tree uses 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 *> generateTrees(int n) { 13 return generateTreesRe(1, n); 14 } 15 16 vector<TreeNode*> generateTreesRe(int l, int r) 17 { 18 vector<TreeNode*> res; 19 if(l > r) { 20 res.push_back(NULL); 21 return res; 22 } 23 24 for(int k = l; k <= r; k++) { 25 vector<TreeNode*> left = generateTreesRe(l, k-1); 26 vector<TreeNode*> right = generateTreesRe(k+1, r); 27 for(int i = 0; i < left.size(); i++) { 28 for(int j = 0; j < right.size(); j++) { 29 TreeNode* root = new TreeNode(k); 30 root->left = left[i]; 31 root->right = right[j]; 32 res.push_back(root); 33 } 34 } 35 } 36 return res; 37 } 38 };