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.
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
----------------------- thinking ----------------------------------
https://oj.leetcode.com/discuss/9790/java-solution-with-dp------------------------- codes -----------------------------------
/**
* 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 *> generateTrees(int n) {
vector<TreeNode *> trees[n+1];
trees[0].push_back(NULL);
trees[1].push_back(new TreeNode(1));
for (int i = 2; i <n+1; i++) {
for (int j = 1; j <= i; j++) {
for (int left = 0; left < trees[j-1].size(); left++) {
for (int right = 0; right < trees[i-j].size(); right++) {
TreeNode *newroot = new TreeNode(j);
//trick here, we don't need to clone the left side trees since they are kepted the same
newroot->left = trees[j-1][left];
newroot->right = cloneTree(trees[i-j][right], j);
trees[i].push_back(newroot);
}
}
}
}
return trees[n];
}
TreeNode * cloneTree(TreeNode* root, int offset) {
if (root == NULL) {
return NULL;
}
TreeNode *newroot = new TreeNode(root->val + offset);
newroot->left = cloneTree(root->left, offset);
newroot->right = cloneTree(root->right, offset);
return newroot;
}
};
No comments:
Post a Comment