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

猜你喜欢

转载自www.cnblogs.com/zywscq/p/10754188.html