题目:
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 withN
nodes. Each element of the answer is the rootnode
of one possible tree.
Each node of each tree in the answer must havenode.val = 0
.
You may return the final list of trees in any order.
Example 1:
Input: 7 Output: [[0,0,0,null,null,0,0,null,null,0,0],[0,0,0,null,null,0,0,0,0],[0,0,0,0,0,0,0], [0,0,0,0,0,null,null,null,null,0,0],[0,0,0,0,0,null,null,0,0]]
Explanation:
Note:
1 <= N <= 20
解释:
返回N个结点能构成的所有的满二叉树的形式。
满二叉树:要求所有的结点都有0个或者2个叶子结点。
完全二叉树:若设二叉树的深度为h,除第 h 层外,其它各层 (1~h-1) 的结点数都达到最大个数,第 h 层所有的结点都连续集中在最左边。
(1)所有的叶结点都出现在第k层或k-l层(层次最大的两层)
(2)对任一结点,如果其右子树的最大层次为L,则其左子树的最大层次为L或L+l。
也就是完全二叉树比满二叉树的形式更加集中。
需要注意的是,如果N是偶数,则一定不能构成满二叉树。
python代码:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def __init__(self):
#记忆化一下,因为会有很多重复计算
self._dict={1:[TreeNode(0)]}
def allPossibleFBT(self, N):
"""
:type N: int
:rtype: List[TreeNode]
"""
result=[]
#偶数个结点一定无法构成满二叉树。
if N<=0 or N%2==0:
return result
#这里很重要
if N in self._dict:
return self._dict[N];
for l in range(1,N,2):
for left in self.allPossibleFBT(l):
for right in self.allPossibleFBT(N-1-l):
root=TreeNode(0)
root.left=left
root.right=right
result+=[root]
self._dict[N]=result;
return result
c++代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
#include <map>
using namespace std;
class Solution {
public:
//记忆化
map<int,vector<TreeNode*>>_map;
Solution()
{
TreeNode* tmp=new TreeNode(0);
_map[1]={tmp};
}
vector<TreeNode*> allPossibleFBT(int N) {
vector<TreeNode*>result;
if (N<=0|| N %2==0)
return result;
if (_map.count(N))
{
return _map[N];
}
for (int l=1;l<N;l+=2)
{
vector<TreeNode*> left_list=allPossibleFBT(l);
vector<TreeNode*> right_list=allPossibleFBT(N-1-l);
for (auto left:left_list)
{
for(auto right:right_list)
{
TreeNode* root=new TreeNode(0);
root->left=left;
root->right=right;
result.push_back(root);
}
}
}
_map[N]=result;
return result;
}
};
解释:
对于这种会重复计算的问题,用一个全局的字典记录已经计算好的值可以节省大量的时间。