894. All Possible Full Binary Trees——tree

时间:2019-02-19
本文章向大家介绍894. All Possible Full Binary Trees——tree,主要包括894. All Possible Full Binary Trees——tree使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

题目分析:输出所有的完全二叉树

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