<p>Given an integer <code>n</code>, return <em>all the structurally unique <strong>BST&#39;</strong>s (binary search trees), which has exactly </em><code>n</code><em> nodes of unique values from</em> <code>1</code> <em>to</em> <code>n</code>. Return the answer in <strong>any order</strong>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/01/18/uniquebstn3.jpg" style="width: 600px; height: 148px;" />
<pre>
<strong>Input:</strong> n = 3
<strong>Output:</strong> [[1,null,2,null,3],[1,null,3,2],[2,1,3],[3,1,null,null,2],[3,2,null,1]]
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> n = 1
<strong>Output:</strong> [[1]]
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= n &lt;= 8</code></li>
</ul>

/**
 * 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) {
        return generateTrees_i(n,0);
    }
    vector<TreeNode*> generateTrees_i(int n,int app){
        vector<TreeNode*> p;
        if(n==0){
            return {};
        }
        if(n==1){
            TreeNode* element=new TreeNode(1);
            element->val=element->val+app;
            return {element};
        }
        for(int k=1;k<=n;k++){
            vector<TreeNode*> alpha=generateTrees_i(n-k,k+app);
            vector<TreeNode*> beta=generateTrees_i(k-1,0+app);
            if(beta.size() && alpha.size()){
            for(int i=0;i<alpha.size();i++){
                for(int j=0;j<beta.size();j++){
                    TreeNode* root=new TreeNode(k);
                    root->val=root->val+app;
                    root->right=alpha[i];
                    root->left=beta[j];
                    p.push_back(root);
                }
            }}
            else if(beta.size()==0 && alpha.size()!=0){
                for(int i=0;i<alpha.size();i++){
                    TreeNode* root=new TreeNode(k);
                    root->val=root->val+app;
                    root->right=alpha[i];
                    p.push_back(root);
                }
            }
            else if (alpha.size()==0 && beta.size()!=0){
                for(int i=0;i<beta.size();i++){
                    TreeNode* root=new TreeNode(k);
                    root->val=root->val+app;
                    root->left=beta[i];
                    p.push_back(root);
                }
            }

        }
        return p;  
    }
};
19600