将1到n的序列,选定任意一个数为根节点,然后分别求解左右字树的解。
同时递归求解左右子树。
# 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 generateTrees(self, n: int) -> List[TreeNode]:
if n <= 0:
return []
return self.helper(1, n)
def helper(self, start, end):
if start > end:
return [None]
result = []
for i in range(start, end+1):
left = self.helper(start, i-1)
right = self.helper(i+1, end)
for e in left:
for f in right:
node = TreeNode(i)
node.left = e
node.right = f
result.append(node)
return result
网友评论