题解 | #从中序与后序遍历序列构造二叉树# Python3
从中序与后序遍历序列构造二叉树
https://www.nowcoder.com/practice/ab8dde7f01f3440fbbb7993d2411a46b
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param inorder int整型一维数组 中序遍历序列
# @param postorder int整型一维数组 后序遍历序列
# @return TreeNode类
#
class Solution:
def buildTree(self , inorder: List[int], postorder: List[int]) -> TreeNode:
# write code here
# inorder 左中右 postoder 左右中
# postorder 确定根节点,inorder确定左右节点个数,
if len(postorder) == 0: return None
root = TreeNode(postorder[-1])
root_index = inorder.index(root.val)
root.left = self.buildTree(inorder[:root_index],postorder[:root_index])
root.right = self.buildTree(inorder[root_index+1:],postorder[root_index:-1])
return root
