My C++ solution


  • 3
    Z
    class Solution {
    private:
        vector<TreeNode *> getTrees(int n, int offset) {
            vector<TreeNode *> ans;
            if(n == 0) {
                ans.push_back(nullptr);
                return ans;
            }
            int i, j, k;
            for(i=1; i<=n; i++) {
                vector<TreeNode *> left = getTrees(i-1, offset);
                vector<TreeNode *> right = getTrees(n-i, i+offset);
                for(j=0; j<left.size(); j++) {
                    for(k=0; k<right.size(); k++) {
                        TreeNode *root = new TreeNode(i+offset);
                        root->left = left[j];
                        root->right = right[k];
                        ans.push_back(root);
                    }
                }
            }
            return ans;
        }
    public:
        vector<TreeNode *> generateTrees(int n) {
            return getTrees(n, 0);
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.