Unique Binary Search Tree II
Question
Given n, generate all structurally unique BST's (binary search trees) that store values 1...n.
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
Thoughts
对这个数字序列,遍历所有可以做root的,并且对左右所有可以做child的也遍历
Solution
class Solution:
# @paramn n: An integer
# @return: A list of root
def generateTrees(self, n):
# write your code here
return self.generate(1, n)
def generate(self, start, end):
result = []
if start > end:
result.append(None)
return result
for i in range(start, end+1):
left = self.generate(start, i - 1)
right = self.generate(i+1, end)
for l in left:
for r in right:
root = TreeNode(i)
root.left = l
root.right = r
result.append(root)
return result