Question
Given an integer n, generate all structurally unique BST’s (binary search trees) that store values 1…n.
给出一个整数n,请你生成所有的不重复的BST的结构(即构建树),它的结点值为1…n
Example
Given n = 3, your program should return all 5 unique BST’s shown below.
Solution
- 动态规划解。思路还是之前的思路,把每个结点作为根节点,然后分别计算其左子树和右子树,因为这里要把每种情况都构建出来。所有我们在递归过程中把每棵树都构建出来并加入列表
class Solution(object):
def generateTrees(self, n):
"""
:type n: int
:rtype: List[TreeNode]
"""
if n == 0: return []
return self.solve(1, n)
def solve(self, start, end):
res = []
# 如果没有结点了就返回空结点
if start > end:
return [None]
# 如果只有一个结点则直接返回该结点
if start == end:
return [TreeNode(start)]
# 分别以1...n为根节点
for root_index in range(start, end + 1):
# 得到左子树列表
lsubtree = self.solve(start, root_index - 1)
# 得到右子树列表
rsubtree = self.solve(root_index + 1, end)
# 构建树
for lnode in lsubtree:
for rnode in rsubtree:
root = TreeNode(root_index)
root.left = lnode
root.right = rnode
res.append(root)
return res