Leetcode 894.所有可能的滿二叉樹
1 題目描述(Leetcode題目鏈接)
滿二叉樹是一類二叉樹,其中每個結點恰好有 0 或 2 個子結點。
返回包含 N 個結點的所有可能滿二叉樹的列表。 答案的每個元素都是一個可能樹的根結點。
答案中每個樹的每個結點都必須有 node.val=0。
你可以按任何順序返回樹的最終列表。
輸入:7
輸出:
[
[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]
]
解釋:
提示:1 <= N <= 20
2 題解
顯然爲偶數不可能組成一個滿二叉樹。用遞歸來做,對於一個,遞歸的左子樹和右子樹節點數量,例如,就分爲三種組合。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def allPossibleFBT(self, N: int) -> List[TreeNode]:
if N%2 == 0:
return []
if N == 1:
return [TreeNode(0)]
res = []
for i in range(1, N, 2):
lchild = self.allPossibleFBT(i)
rchild = self.allPossibleFBT(N-i-1)
for l in lchild:
for r in rchild:
root = TreeNode(0)
root.left = l
root.right = r
res.append(root)
return res