Posted on

Description

Submission

/**
 * 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 n) {
        if(n == 0) return {};
        return generateTrees(1, n);
    }

    vector<TreeNode*> generateTrees(int l, int r) {
        if(l > r) return {nullptr};

        vector<TreeNode*> curAll;

        for(int i = l; i <= r; ++i) {
            vector<TreeNode*> leftAll = generateTrees(l, i - 1);
            vector<TreeNode*> rightAll = generateTrees(i + 1, r);


            for(TreeNode* left: leftAll) {
                for(TreeNode* right: rightAll) {
                    TreeNode* root = new TreeNode(i);
                    root->left = left;
                    root->right = right;
                    curAll.push_back(root);
                }
            }
        }
        return curAll;
    }
};

Leave a Reply

Your email address will not be published. Required fields are marked *