So I was doing this question on Leetcode, where given the inorder and preorder traversal of a binary tree, we have to build the tree. So I wrote the code, and the solution is working, but I am a bit stuck while calculating time complexity of the solution. Could someone please provide an insight into calculating it? Any input is appreciated. Here is the code:
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