Given an integern, generate all structurally uniqueBST's(binary search trees) that store values 1...n.
For example,
Givenn= 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
Solution:
if start > end:
return \[None\] 非常重要,因为如果start > end 说明没有任何所以需要补入Noned的节点进入list 这样才可以补空位。
常犯的错误,看见start end, 就直接二分法了,应该还是从start 开始一个一个的遍历。
double for means Left * Right
DFS + 分治
class Solution(object):
def generateTrees(self, n):
"""
:type n: int
:rtype: List[TreeNode]
"""
if n <= 0 :
return []
return self.dfs(1, n)
def dfs(self, start, end):
if start > end: return [None]
res = []
for rootval in range(start, end+1):
LeftTree = self.dfs(start, rootval-1)
RightTree = self.dfs(rootval+1, end)
for i in LeftTree:
for j in RightTree:
root = TreeNode(rootval)
root.left = i
root.right = j
res.append(root)
return res