894. All Possible Full Binary Trees
# 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[Optional[TreeNode]]:
if n == 0:
return []
if n == 1:
return [TreeNode()]
if n == 2:
return []
res = []
for i in range(1, n-1):
left = self.allPossibleFBT(i)
right = self.allPossibleFBT(n-i-1)
if not left or not right:
continue
for l in left:
for r in right:
node = TreeNode()
node.left = l
node.right = r
res.append(node)
return res
Optimize
Select tags
0/5
# 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:
@cache
def allPossibleFBT(self, n: int) -> List[Optional[TreeNode]]:
if n % 2 == 0: return []
if n == 1: return [TreeNode(0)]
res = []
for i in range(1, n, 2):
for left in self.allPossibleFBT(i):
for right in self.allPossibleFBT(n - 1 - i):
root = TreeNode(0)
root.left = left
root.right = right
res.append(root)
return res