#105
Construct Binary Tree from Preorder and Inorder Traversal
medium· Treesruns: 0Given two integer arrays preorder and inorder representing the preorder and inorder traversals of a binary tree, construct and return the binary tree.
sign in to paste and practice your own solution
wpm 0acc 100%time 0:000 / 427
class Solution:
def buildTree(
self, preorder: list[int], inorder: list[int]
) -> TreeNode | None:
if not preorder or not inorder:
return None
root = TreeNode(preorder[0])
mid = inorder.index(preorder[0])
root.left = self.buildTree(preorder[1 : mid + 1], inorder[:mid])
root.right = self.buildTree(preorder[mid + 1 :], inorder[mid + 1 :])
return root
click the box to focus · tab inserts 4 spaces · backspace to correct · esc to pause
desktop only
codedrill is a typing game and needs a real keyboard. open this on a laptop or desktop to practice.
you can still browse problems and sections from your phone.