Medium
n==0
的情况,直接返回空树,即None
以上,尝试写一下代码,AC!
这道题难点就是要,理解节点的左右子树自由组合的过程,最好还是在纸上推演一下,写出代码之后debug,会清晰很多
python3
class Solution:
def generateTrees(self, n: int) -> List[TreeNode]:
def helper(lo,hi):
res = []
if lo > hi:
res.append(None)
return res
for i in range(lo,hi+1):
left_list = helper(lo,i-1)
right_list = helper(i+1,hi)
for l in left_list:
for r in right_list:
node = TreeNode(i,l,r)
res.append(node)
return res
if n is 0:
return None
return helper(1,n)