95. 不同的二叉搜索树 II

题目

``````输入：3

[
[1,null,3,2],
[3,2,null,1],
[3,1,null,null,2],
[2,1,3],
[1,null,2,null,3]
]

1         3     3      2      1
\       /     /      / \      \
3     2     1      1   3      2
/     /       \                 \
2     1         2                 3``````

代码实现

``````# 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 []

def get_all_bts(left, right):
if left > right:
return [None]
if left == right:
return [TreeNode(left)]

ans = []
for i in range(left, right+1):
# 开始进行枚举
# 左子树所有可能的情况
left_sub_trees = get_all_bts(left, i-1)
# 右子树所有可能的情况
right_sub_trees = get_all_bts(i+1, right)
# 从左子树跟右子树集合当中各取一种，与根节点构成二叉搜索树
for left_sub_tree in left_sub_trees:
for right_sub_tree in right_sub_trees:
root = TreeNode(i)
root.left = left_sub_tree
root.right = right_sub_tree
ans.append(root)
return ans
return get_all_bts(1, n)``````

35 声望
5 粉丝
0 条评论