1、[106]Construct Binary Tree from Inorder and Postorder Traversal
1.1 题目描述
# Given two integer arrays inorder and postorder where inorder is the inorder
# traversal of a binary tree and postorder is the postorder traversal of the same
# tree, construct and return the binary tree.
#
#
# Example 1:
#
#
# Input: inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]
# Output: [3,9,20,null,null,15,7]
#
#
# Example 2:
#
#
# Input: inorder = [-1], postorder = [-1]
# Output: [-1]
#
#
#
# Constraints:
#
#
# 1 <= inorder.length <= 3000
# postorder.length == inorder.length
# -3000 <= inorder[i], postorder[i] <= 3000
# inorder and postorder consist of unique values.
# Each value of postorder also appears in inorder.
# inorder is guaranteed to be the inorder traversal of the tree.
# postorder is guaranteed to be the postorder traversal of the tree.
#
from typing import List, Optional
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
# leetcode submit region begin(Prohibit modification and deletion)
# 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]:
mid_map = {}
for i, v in enumerate(inorder):
mid_map[v] = i
root = TreeNode(postorder[-1])
in_root_index = mid_map[root.val]
left_inorder = inorder[:in_root_index]
right_inorder = inorder[in_root_index + 1:]
if left_inorder:
root.left = self.buildTree(left_inorder, postorder[:len(left_inorder)])
if right_inorder:
root.right = self.buildTree(right_inorder, postorder[len(left_inorder):-1])
return root
# leetcode submit region end(Prohibit modification and deletion)
if __name__ == '__main__':
inorder = [9, 3, 15, 20, 7]
postorder = [9, 15, 7, 20, 3]
so = Solution()
res = so.buildTree(inorder, postorder)
test = 1
1.2 解题思路
- 根据后序遍历确定确定
根节点
。 - 根据
根节点
划分中序遍历数组
。 - 根据
中序遍历的数组长度
切分后序遍历
。 - 中序遍历与后序遍历的
左子树
数组长度相同。
- 将数组划分为子任务,继续递归求解。