题目地址:https://leetcode.com/problems/all-possible-full-binary-trees/description/
对二叉树的递归构造。
对奇数枚举左右子树点的个数,偶数不符合条件直接返回
/**
* 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*> allPossibleFBT(int N) {
vector<TreeNode*> ans;
if(N%2==0)
return ans;
if(N==1)
{
TreeNode *root=new TreeNode(0);
ans.push_back(root);
return ans;
}
for(int i=1;i<N;i+=2)
{
vector<TreeNode*> left=allPossibleFBT(i);
vector<TreeNode*> right=allPossibleFBT(N-i-1);
for(int l=0;l<left.size();l++)
{
for(int r=0;r<right.size();r++)
{
TreeNode *root=new TreeNode(0);
root->left=left[l];
root->right=right[r];
ans.push_back(root);
}
}
}
return ans;
}
};