Unique Binary Search Trees II *
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3 if start > end:
return \[None\] 非常重要,因为如果start > end 说明没有任何所以需要补入Noned的节点进入list 这样才可以补空位。
常犯的错误,看见start end, 就直接二分法了,应该还是从start 开始一个一个的遍历。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 resLast updated