前序的第一个节点就是根节点,再去中序里面找到根节点的索引,那根节点之前的部分就是左子树,根节点后部分就是右子树
找索引用哈希表,降低时间复杂度
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
if not preorder:return None
dic = {element : i for i, element in enumerate(inorder)} #存索引
def my_build(left,right):
if(left < right):
top = preorder.pop(0)
root = TreeNode(top) #根节点
index = dic[root.val] #分隔左子树和右子树
root.left = my_build(left, index)
root.right = my_build(index + 1, right)
return root
return my_build(0, len(inorder))