Leetcode 894. All Possible Full Binary Trees

递归

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
import functools
class Solution:
    @functools.lru_cache()
    def allPossibleFBT(self, N: int) -> List[TreeNode]:
        ans=[]
        if N==1:
            return [TreeNode(0)]
        
        for i in range(0,N):
            if (i==0 or i%2==1) and ((N-1-i)==0 or (N-1-i)%2==1):
                print(i,N-1-i)
                for l in self.allPossibleFBT(i):
                    for r in self.allPossibleFBT(N-1-i):
                        root=TreeNode(0)
                        root.left=l
                        root.right=r
                        ans.append(root)
            else:
                continue
            
        return ans

 

posted @ 2019-04-23 04:16  周洋  阅读(182)  评论(0编辑  收藏  举报