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.
Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7] Output: [3,9,20,null,null,15,7]
class Solution:
def buildTree(self, p: List[int], i: List[int]) -> Optional[TreeNode]:
if not p or not i:
return None
# p = [3,9,20,15,7]
# i = [9,3,15,20,7]
root = TreeNode(p[0])
mid = i.index(p[0]) # mid = 1
root.left = self.buildTree(p[1:mid+1],i[:mid])
root.right = self.buildTree(p[mid+1:],i[mid+1:])
return root
Explaination :
Comments
Post a Comment