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: this problem can be solved recursively; if the values of the nodes in the tree we want to generate are in the range of [start, end]; then the values of the nodes in the left subtree are in the range of [start, i-1], and the values of the nodes in the right subtree are in the range of [i+1, end], where i is the value of the root and start \le i \le end.
/**
* 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 *> generateTreesHelper(int start, int end) {
// Note: The Solution object is instantiated only once and is reused by each test case.
vector<TreeNode *> ret;
if(start>end){
ret.push_back(NULL);
return ret;
}
for(int i=start; i<=end; i++){
vector<TreeNode *> leftTree = generateTreesHelper(start, i-1);
vector<TreeNode *> rightTree = generateTreesHelper(i+1, end);
for(int j=0; j<leftTree.size(); j++){
for(int k=0; k<rightTree.size(); k++){
TreeNode* root = new TreeNode(i);
root->left = leftTree[j];
root->right = rightTree[k];
ret.push_back(root);
}
}
}
return ret;
}
vector<TreeNode *> generateTrees(int n) {
// Note: The Solution object is instantiated only once and is reused by each test case.
return generateTreesHelper(1, n);
}
};
No comments:
Post a Comment