python
# 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: List[int], inorder: List[int]) -> Optional[TreeNode]:
python
class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
if not preorder:
return None
left_size = inorder.index(preorder[0])
left = self.buildTree(preorder[1:1+left_size],inorder[:left_size])
right = self.buildTree(preorder[1+left_size:],inorder[1+left_size:])
return TreeNode(preorder[0],left,right)
时间复杂度:n的平方,其中 n 为 preorder的长度。最坏情况下二叉树是一条链,我们需要递归 O(n)次,每次都需要 O(n)的时间查找 preorder[0]和复制数组。
空间复杂度:n的平方
python
class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
index = {x:i for i,x in enumerate(inorder)}
def dfs(pre_l:int,pre_r:int,in_l:int,in_r:int) -> Optional[TreeNode]:
if pre_l == pre_r:
return None
left_size = index[preorder[pre_l]] - in_l #左子树大小
left = dfs(pre_l + 1,pre_l+1+left_size,in_l,in_l+left_size)
right= dfs(pre_l+1+left_size,pre_r,in_l+1+left_size,in_r)
return TreeNode(preorder[pre_l],left,right)
return dfs(0,len(preorder),0,len(inorder)) #左闭右开区间
速度快了很多41ms