应用题-二叉树专题-从中序与后序遍历序列构造二叉树

管理员
```python # 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]: # 查询优化 每次递归都需要查询根节点的位置 所以预处理索引 inorder_indexes = { val: i for i, val in enumerate( inorder ) } def build( inorder_start, inorder_end, postorder_start, postorder_end ): if inorder_start >= inorder_end or postorder_start >= postorder_end: return None # 利用后序找到根节点 根据根节点的位置 拆分左右子树 # 使用四个指针标记中序和后序的开始结束位置 所以操作要基于指针范围来 root_val = postorder[ postorder_end - 1 ] root_node = TreeNode( root_val ) root_index = inorder_indexes[ root_val ] left_size = root_index - inorder_start root_node.left = build( inorder_start, root_index, postorder_start, postorder_start + left_size ) root_node.right = build( root_index + 1, inorder_end, postorder_start + left_size, postorder_end - 1 ) return root_node return build( 0, len( inorder ), 0, len( postorder ) ) ```
评论 0

发表评论 取消回复

Shift+Enter 换行  ·  Enter 发送
还没有评论,来发表第一条吧