思路:二叉树的知识。return [None, ]表示字数为空,每次都返回一个子树的列表,其中子树是由左子树和右子树整合得到的。
题目:给定一个整数 n,生成所有由 1 … n 为节点所组成的二叉搜索树。
示例:
输入: 3
输出:
[
[1,null,3,2],
[3,2,null,1],
[3,1,null,null,2],
[2,1,3],
[1,null,2,null,3]
]
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def generateTrees(self, n: int) -> List[TreeNode]:
def generatetreess(start, end):
if start > end:
return [None, ]
all_trees = []
for i in range(start, end + 1):
left_tree = generatetreess(start, i - 1)
right_tree = generatetreess(i + 1, end)
# print(i)
for l in left_tree:
for r in right_tree:
cur = TreeNode(i)
cur.left = l
cur.right = r
all_trees.append(cur)
return all_trees
return generatetreess(1, n) if n else []
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/unique-binary-search-trees-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。