1,题目要求
A full binary tree is a binary tree where each node has exactly 0 or 2 children.
Return a list of all possible full binary trees with N nodes. Each element of the answer is the root node of one possible tree.
Each node of each tree in the answer must have node.val = 0.
You may return the final list of trees in any order.
给出树的节点的数量,找到所有可能的满二叉树的形式。
2,题目思路
对于这道题,可以利用递归的方法,依次寻找节点的左右孩子的形式。
用allPossibleFBT(i)和allPossibleFBT(N-i)的分别表示左子树和右子树。
左子树1个、3个、5个。。。右子树就是N-1个、N-3个、N-5个。。。
于是,用这种递归的办法,来找到所有符合条件的树。
3,程序源码
class Solution {
public:
vector<TreeNode*> allPossibleFBT(int N) {
vector<TreeNode*> res;
if(N == 1)
{
res.push_back(new TreeNode(0));
return res;
}
N--;
for(int i = 1;i < N;i+=2) //每次+2
{
vector<TreeNode*> ln = allPossibleFBT(i); //递归部分
vector<TreeNode*> rn = allPossibleFBT(N-i);
for(TreeNode* ll : ln)
for(TreeNode* rr : rn)
{
TreeNode* node = new TreeNode(0);
node->left = ll;
node->right = rr;
res.push_back(node);
}
}
return res;
}
};