Leetcode 894.所有可能的滿二叉樹(All Possible Full Binary Trees)

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 題解

  顯然NN爲偶數不可能組成一個滿二叉樹。用遞歸來做,對於一個NN,遞歸NN的左子樹和右子樹節點數量,例如N=7N=7,就分爲三種組合(1,5),(3,3),(5,1)(1,5),(3,3),(5,1)

# 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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章