解题思路:
1.后序序列的最后一个元素为二叉树的根结点;
2.用此根节点构建一颗新二叉树,用作root.val,并用其划分中序序列的左子树与右子树;
3.中序序列左子树节点个数 == 后序序列左子树个数;
4.以3特点划分后序遍历的左子树与右子树;
5.将划分好的inorder_left postorder_left 传入递归函数,重复1-4;
6.将划分好的inorder_right postorder_right 传入递归函数,重复1-4;
7.最终return root。
注意:
root作为根节点所引导的二叉树,在各层递归函数不断地return的过程中,不断“羽翼丰满“,直到最后构建成一颗完整的二叉树。
# 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 postorder:
return None
rootVal = postorder[-1]
root = TreeNode(rootVal)
#这一步为对叶子结点的优化
if len(postorder) == 1:
return root
#取根节点在先序遍历的index
rootVal_idx = inorder.index(rootVal)
inorder_left = inorder[:rootVal_idx]
inorder_right = inorder[rootVal_idx + 1:]
postorder_left = postorder[:len(inorder_left)]
postorder_right = postorder[len(inorder_left): -1]
root.left = self.buildTree(inorder_left, postorder_left)
root.right = self.buildTree(inorder_right, postorder_right)
return root