LeetCode 105. 从前序与中序遍历序列构造二叉树
根据一棵树的前序遍历与中序遍历构造二叉树。
注意:
你可以假设树中没有重复的元素。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
Code
def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
if len(inorder)==0 or len(preorder)==0:
return None
root=TreeNode(preorder[0])#root节点
mid=inorder.index(root.val)
root.left=self.buildTree(preorder[1:mid+1],inorder[:mid]) #构建左节点
root.right=self.buildTree(preorder[mid+1:],inorder[mid+1:])#构建右节点
return root
想法
前序遍历:遍历顺序为 父节点 -> 左子节点 -> 右子节点
中序遍历:遍历顺序为 左子节点 -> 父节点 -> 右子节点
左子树节点个数 = 中序遍历中根节点索引 - 开始位置
右子树节点个数 = 结束位置 - 中序遍历中根节点索引