题目
 
 
思路
思路同 从前序与中序遍历序列构造二叉树,区别是root需要从postorder列表的尾部取。
# 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:
            return None
        # 1.取出后序节点创建新树的节点
        root = TreeNode(postorder[-1])
        
        # 2.找到新树的节点在中序中的索引
        in_index = inorder.index(root.val)
        
        # 3.分割中序序列
        in_left = inorder[:in_index]
        in_right = inorder[in_index+1:]
        # 4.分割后序序列
        pre_left = postorder[:len(in_left)]
        pre_right = postorder[len(in_left):-1]
        # 5.继续递归建立整颗新树
        root.left = self.buildTree(in_left, pre_left)
        root.right = self.buildTree(in_right, pre_right)
        return root


















