617. Merge Two Binary Trees
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.
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]]
根据输入节点的个数求所有可能的满二叉树的情况。
左右子树的节点个数都是奇数。左子树节点个数为奇数i,右子树节点个数为N-1-i。
循环所有的奇数节点,用递归构造左右子树。每次递归返回一个数组,是所有两二叉树情况的节点,左右节点分别存在两个数组中。遍历所有的左右节点,插入到二叉树的左右子树。1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25var allPossibleFBT = function(N) {
var result = []
if(N==1){
var leafnode = new TreeNode(0)
result.push(leafnode)
return result
}
if(N%2==0 || N<1) {
return result
}
for(var i=1; i<N ;i+=2){
var leftlist = allPossibleFBT(i)
var rightlist = allPossibleFBT(N-i-1)
for(var j=0; j<leftlist.length; j++){
for(var k=0; k<rightlist.length; k++){
var node = new TreeNode(0)
node.left = leftlist[j]
node.right = rightlist[k]
result.push(node)
}
}
}
return result
};