题目
满二叉树是一类二叉树,其中每个结点恰好有 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]