105. Construct Binary Tree from Preorder and Inorder Traversal
Given two integer arrays
preorder
and inorder
where preorder
is the preorder traversal of a binary tree and inorder
is the inorder traversal of the same tree, construct and return the binary tree.Note: I was using len(inorder) as initial call instead of len(inorder) - 1.
Use hashmap for looking up node in inorder.
I initially missed the recursion base condition termination start > end
def buildTree(self, preorder: List[int], inorder: List[int]):
self.rootIndex = 0
def recurse (start, end):
if start > end:
return None
root = TreeNode(preorder[self.rootIndex])
self.rootIndex += 1
root.left = recurse(start, inorder_index_map[root.val] - 1)
root.right = recurse(inorder_index_map[root.val] + 1, end)
return root
inorder_index_map = {}
for index, value in enumerate(inorder):
inorder_index_map[value] = index
return recurse(0, len(inorder)-1)
Comments
Post a Comment