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
这道题是让我们来构造所有可能的BST,根据BST的定义,我们可以知道某个节点的左子树的所有节点都会小于该节点,右子树所有节点都大于该节点。
所以我们就有思路了,我们按顺序地从1-N,把其中的值当做根节点,然后划分成两个数组,分别是左子树和右子树,然后再对左右使用该方法来构造子树的左子树和右子树,这样递归下去就可以完成所有BST的构造了。
大概写了个简陋的代码,内存消耗貌似有点大,24毫秒只能说是适中吧。。。
/**
* Definition for a binary tree node.
* 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*> res;
for (int i = 1; i <= n; i++) {
vector<TreeNode*> leftNodes = buildTree(1, i - 1);
vector<TreeNode*> rightNodes = buildTree(i + 1, n);
for (auto lnode : leftNodes) {
for (auto rnode : rightNodes) {
TreeNode* pRoot = new TreeNode(i);
pRoot->left = lnode;
pRoot->right = rnode;
res.push_back(pRoot);
}
}
}
return res;
}
static vector<TreeNode*> buildTree(int nStart, int nEnd) {
vector<TreeNode*> res;
for (int i = nStart; i <= nEnd; i++) {
vector<TreeNode*> leftNodes = buildTree(nStart, i - 1);
vector<TreeNode*> rightNodes = buildTree(i + 1, nEnd);
for (auto lnode : leftNodes) {
for (auto rnode : rightNodes) {
TreeNode* pRoot = new TreeNode(i);
pRoot->left = lnode;
pRoot->right = rnode;
res.push_back(pRoot);
}
}
}
if (res.empty()) {
res.push_back(nullptr);
}
return res;
}
};