106. 从中序与后序遍历序列构造二叉树

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 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 inorder==[]: return None # 空
root = TreeNode(postorder[-1]) # 定根节点
if len(inorder)==1: return root # 叶子结点

root_value = postorder[-1]
for index in range(0,len(inorder)): # 找根节点在中序遍历中的位置
if inorder[index]==root_value:
break
left_inorder,right_inorder = inorder[:index],inorder[index+1:] # 再切割
left_postorder,right_postorder = postorder[:index],postorder[index:-1]
root.left = self.buildTree(left_inorder,left_postorder) # 构建树
root.right = self.buildTree(right_inorder,right_postorder)
return root