95. 不同的二叉搜索树 II
题目描述
解题思路
1、定义generateTrees(start, end)函数为生成[start, end]区间的所有可行二叉搜索树,以生成节点i为例:generateTrees(start, i-1)和generateTrees(i+1, end)生成所有左右子树,再排列组合
代码实现
# 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]:
"""
定义generateTrees(start, end)函数
为生成[start, end]区间的所有可行二叉搜索树,
以生成节点i为例:generateTrees(start, i-1)和generateTrees(i+1, end)生成所有左右子树,再排列组合
"""
def generateTrees(start: int, end: int):
if start > end:
return [None, ]
allTrees = []
for i in range(start, end+1):
left = generateTrees(start, i-1)
right = generateTrees(i+1, end)
for l in left:
for r in right:
node = TreeNode(i)
node.left = l
node.right = r
allTrees.append(node)
return allTrees
return generateTrees(1, n) if n else []
参考文献
1、官方题解