leetcode_num95_Unique BT II

Given n, generate all structurally unique BST's (binary search trees) that store values 1...n.

For example,
Given n = 3, your program should return all 5 unique BST's shown below.

   1         3     3      2      1
    \       /     /      / \      \
     3     2     1      1   3      2
    /     /       \                 \
   2     1         2                 3
 
  
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector generateTrees(int n) {
        return generateTrees(1,n);
    }
    vectorgenerateTrees(int s,int e){
        vector res;
        if(s>e)
            res.push_back(0);//the default element is 0
        else if(s==e)
            res.push_back(new TreeNode(s));//new
        else if(sleft=generateTrees(s,i-1);//the left subtrees
                vectorright=generateTrees(i+1,e);//the right subtrees
                for(int j=0;jleft=left[j];
                        proot->right=right[k];
                        res.push_back(proot);
                    }
                }
            }
        }
        return res;
    }
};


你可能感兴趣的:(c++,oj-leetcode)