python-leetcode-从中序与后序遍历序列构造二叉树
106. 从中序与后序遍历序列构造二叉树 - 力扣(LeetCode)
# 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, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]:
if not inorder or not postorder: # 如果任一遍历为空,返回 None
return None
# 根节点是后序遍历的最后一个元素
root_val = postorder.pop()
root = TreeNode(root_val)
# 找到根节点在中序遍历中的位置
root_index = inorder.index(root_val)
# 划分右子树和左子树(注意:先处理右子树,因为后序遍历是左-右-根)
right_inorder = inorder[root_index + 1:]
left_inorder = inorder[:root_index]
# 递归构建右子树和左子树
root.right = self.buildTree(right_inorder, postorder)
root.left = self.buildTree(left_inorder, postorder)
return root