【发布时间】:2021-08-25 10:40:36
【问题描述】:
所以我在 Leetcode 上做这个问题,在给定二叉树的中序和前序遍历的情况下,我们必须构建树。所以我编写了代码,并且解决方案正在运行,但是在计算解决方案的时间复杂度时我有点卡住了。有人可以提供计算它的见解吗?任何输入表示赞赏。代码如下:
class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
def construct(preord, inord, noted):
if preord == []:
return
root = TreeNode(preord[0])
noted.add(preord[0])
index = inord.index(preord.pop(0))
for i in inord[index::-1]:
if preord != [] and i == preord[0]:
root.left = construct(preord, inord, noted)
for i in inord[index + 1:]:
if i in noted:
break
if preord != [] and i == preord[0]:
root.right = construct(preord, inord, noted)
return root
visit = set()
root = construct(preorder, inorder, visit)
return root
【问题讨论】:
-
这能回答你的问题吗? How to find time complexity of an algorithm
标签: algorithm recursion data-structures binary-tree tree-traversal