Given two integer arrays
preorder
andinorder
wherepreorder
is the preorder traversal of a binary tree andinorder
is the inorder traversal of the same tree, construct and return the binary tree.
Time spent: 1h 20m | Runtime: 79.86% | Memory: 96.19%
{left,center,right}
and preorder is {center,left,right}
.Time spent: 15m | Runtime: 11.70% | Memory: 11.04%
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def buildTree(self, preorder, inorder):
return self.buildSubTree(preorder, inorder)
def buildSubTree(self, preorder, inorder):
if not preorder:
return None
# preorder: center, left, right
# inorder: left, center, right
center = preorder[0]
# Everything up to the center.
left_side_inorder = inorder[:inorder.index(center)]
# Skip the first element (center), take the now-known size of
# the left side.
left_side_preorder = preorder[1:1 + len(left_side_inorder)]
# Take everything after the left and center.
right_side_inorder = inorder[inorder.index(center) + 1:]
# Same idea as inorder - take everything after left and center.
right_side_preorder = preorder[1 + len(left_side_inorder):]
return TreeNode(
val=center,
left=self.buildSubTree(left_side_preorder, left_side_inorder),
right=self.buildSubTree(right_side_preorder, right_side_inorder),
)