/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<TreeNode*> generateTrees(int n) {
vector<TreeNode*> ans;
if (n==0) {
return ans;
}
return generateTrees(1, n);
}
private:
vector<TreeNode*> generateTrees(int left, int right) {
//回傳該層的tree
//所以只有最上層才會回傳最後結果
vector<TreeNode*> ans;
if (left > right) {
ans.push_back(NULL);
return ans;
}
//輪流讓i變成root node
for (int ii = left; ii <= right; ii++) {
//兩分: leftTree, righTree兩分到最後, 直到得到leaf
vector<TreeNode*> leftTree = generateTrees(left, ii - 1);
vector<TreeNode*> rightTree = generateTrees(ii + 1, right);
//組合成樹, 返回
for (int i = 0; i < leftTree.size(); i++) {
for (int j = 0; j < rightTree.size(); j++) {
//root是i
TreeNode* node = new TreeNode(ii);
//left
node->left = leftTree[i];
//right
node->right = rightTree[j];
ans.push_back(node);
}
}
}
return ans;
}
};