95. Unique Binary Search Trees II
由于BST的结构性质,所以只要划分左右BFS递归构造即可。
要注意新节点new的时机,不然会丢失结构。
Code
/**
* 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:
//int layer = 1;
vector<TreeNode*> generateTrees(int n) {
if( 0 == n ) return {};
return constructBST(1, n);
}
vector<TreeNode*> constructBST(int l, int r) {
vector<TreeNode*> result, leftChilds, rightChilds;
//cout<< "l : " << l << " r : " << r << endl;
if(l > r) return {nullptr};
for(int i = l; i <= r; i++) {
//TreeNode* curr = new TreeNode(i);这句不能放在这里会丢失结构
//cout<< " i : " << i << " layer: " << layer << endl;
//layer ++;
leftChilds = constructBST(l, i - 1);
rightChilds = constructBST(i + 1, r);
//layer --;
for(int j = 0; j < leftChilds.size(); j++) {
for(int k = 0; k < rightChilds.size(); k++) {
TreeNode* curr = new TreeNode(i);
curr->left = leftChilds[j];
curr->right = rightChilds[k];
result.push_back(curr);
}
}
}
return result;
}
};
```