Given an integer n, generate all structurally unique BST’s (binary search trees) that store values 1 … n.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/unique-binary-search-trees-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
树问题,想到用递归处理
对于空节点,也要在vector中push一个nullptr
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<TreeNode*> generateTrees(int l, int r)
{
vector<TreeNode*> res;
if(l > r){ // 退出条件
res.push_back(nullptr);
// 这里要返回res,但不能是空,否则后面的循环会被跳过
return res;
}
vector<TreeNode*> leftTree, rightTree;
for(int i = l; i <= r; i++){
leftTree = generateTrees(l, i - 1);
rightTree = generateTrees(i + 1, r);
for(TreeNode* leftChild: leftTree){
for(TreeNode* rightChild: rightTree){
TreeNode* root = new TreeNode(i, leftChild, rightChild);
res.push_back(root);
}
}
}
return res;
}
vector<TreeNode*> generateTrees(int n) {
if(!n)
return {};
return generateTrees(1, n);
}
};