Problem:
Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1 ... n.
Example:
Input: 3
Output:
[
[1,null,3,2],
[3,2,null,1],
[3,1,null,null,2],
[2,1,3],
[1,null,2,null,3]
]
Explanation:
The above output corresponds to the 5 unique BST's shown below:
1 3 3 2 1
/ / /
3 2 1 1 3 2
/ /
2 1 2 3
思路:
同样采用递归的思想。若节点(i)作为根节点,则只需分别构造(1, cdots, i-1)的左子树和(i+1, cdots, n)的右子树。同样的,左右子树的构造也是一个递归的过程。
注意:vector<TreeNode*>
数组中储存的是根节点的值,所以要将根和左子树及右子树连起来时,只需分别将存储左右子树的vector<TreeNode*>left, right
中的元素遍历一遍,作为根的左右子节点即构造完毕。
Solution (C++):
public:
vector<TreeNode*> generateTrees(int n) {
if (n == 0) return vector<TreeNode*> {};
return genTrees(1, n);
}
private:
vector<TreeNode*> genTrees(int start, int end) {
vector<TreeNode*> bst;
vector<TreeNode*> left, right;
if (start > end) {
bst.push_back(NULL);
return bst;
}
if (start == end) {
TreeNode* s = new TreeNode(start);
bst.push_back(s);
return bst;
}
for (int i = start; i <= end; ++i) { //以i为根
left = genTrees(start, i-1);
right = genTrees(i+1, end);
for (auto lnode: left) {
for (auto rnode: right) {
TreeNode* root = new TreeNode(i);
root->left = lnode;
root->right = rnode;
bst.push_back(root);
}
}
}
return bst;
}
性能:
Runtime: 20 ms Memory Usage: 19.1 MB