894. All Possible Full Binary Trees(python+cpp)
阿新 • • 發佈:2018-11-16
題目:
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;
}
};
解釋:
對於這種會重複計算的問題,用一個全域性的字典記錄已經計算好的值可以節省大量的時間。