题目描述
给定一个整数 n,生成所有由 1 … n 为节点所组成的二叉搜索树。
递归
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def generateTrees(self, n: int) -> List[TreeNode]:
def build_tree(start,end):
possibility=[]
if start > end:
return [None,]
for i in range(start,end+1):
left_tree=build_tree(start,i-1)
# root=TreeNode(i)
right_tree=build_tree(i+1,end)
for a in left_tree:
for b in right_tree:
root=TreeNode(i)
root.left=a
root.right=b
possibility.append(root)
return possibility
return build_tree(1,n) if n else []
执行用时 :96 ms, 在所有 Python3 提交中击败了10.39%的用户
内存消耗 :15 MB, 在所有 Python3 提交中击败了8.09%的用户
这个是看题解的思路写的,之前也想到用递归来解决但是没有想的这么巧妙
代码主要思想就是定义一个函数来返回一定范围内所有可能的二叉搜索树。先从1到n之间找一个节点,左边和右边各利用递归求出各自所有可能的子树,然后用两个循环来拼接两个儿子树和节点。
现在想想,应该要注意到递归的函数内调用是利用果来解决因,明确好函数的目的之后再调用函数。像这个代码里面对左儿子和右儿子的求法就是假装已经知道了结果来使用它。
递归第一次错误
for i in range(start,end+1):
left_tree=build_tree(start,i-1)
root=TreeNode(i)
right_tree=build_tree(i+1,end)
for a in left_tree:
for b in right_tree:
root.left=a
root.right=b
possibility.append(root)
在这个片段里,我先把root给定义了然后再拼接。这样子的后果就是之后拼接完成后导入到列表中的树都是同一地址的树,而不是另外的树。也就是说在第二次以及之后的拼接过程中,以及导入的树会被干扰,得出错误的答案