Given n, generate all structurally unique BST's (binary search trees) that store values 1...n.
For example,
Given n = 3, your program should return all 5 unique BST's shown below.
1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ \ 2 1 2 3
给出N个节点的二叉搜索树的所有形态~每次选取一个结点做为根,然后递归求解左右子树的所有形态~
注意点:helper函数里l > r 时,return [None] ,是用来表示空树,这样也可以保证下面循环时即使一边是空树,也会跑另一边
class Solution:
# @return a list of tree node
def generateTrees(self, n):
return self.helper(1, n)
def helper(self, l, r):
if l > r:
return [None]
res = []
for rootVal in xrange(l, r + 1):
leftList = self.helper(l, rootVal - 1)
rightList = self.helper(rootVal + 1, r)
for i in leftList:
for j in rightList:
root = TreeNode(rootVal)
root.left = i
root.right = j
res.append(root)
return res