Leetcode-894. 所有可能的满二叉树 All Possible Full Binary Trees

题目

满二叉树是一类二叉树,其中每个结点恰好有 0 或 2 个子结点。
返回包含 N 个结点的所有可能满二叉树的列表。 答案的每个元素都是一个可能树的根结点。
答案中每个树的每个结点都必须有 node.val=0。
你可以按任何顺序返回树的最终列表。
链接:https://leetcode.com/problems/all-possible-full-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:

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:在这里插入图片描述

思路及代码

递归
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def allPossibleFBT(self, N: int) -> List[TreeNode]:
        N -= 1
        if not N:
            return [TreeNode(0)]
        trees = []
        for i in range(1,N,2):
            for left in self.allPossibleFBT(i):
                for right in self.allPossibleFBT(N-i):
                    root = TreeNode(0)
                    root.left = left
                    root.right = right
                    trees += [root]
        return trees
利用Memory降低复杂度
class Solution:
    def allPossibleFBT(self, N: int) -> List[TreeNode]:
        def buildTree(n):
            trees = []
            for i in range(1,n,2):
                for left in memo[i]:
                    for right in memo[n-i-1]:
                        root = TreeNode(0)
                        root.left = left
                        root.right = right
                        trees.append(root)
            memo[n] = trees
        if N%2 == 0: return []
        memo = {1:[TreeNode(0)]}
        for i in range(3,N+1,2):
            buildTree(i)
        return memo[N]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值