51. Leetcode 106. 从中序与后序遍历序列构造二叉树 (二叉树-二叉树构建)
作者:互联网
给定两个整数数组 inorder 和 postorder ,其中 inorder 是二叉树的中序遍历, postorder 是同一棵树的后序遍历,请你构造并返回这颗 二叉树 。
示例 1:
输入:inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]
输出:[3,9,20,null,null,15,7]
示例 2:
输入:inorder = [-1], postorder = [-1]
输出:[-1]
# 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]) -> TreeNode:
if not postorder:
return None
root = TreeNode(postorder[-1])
rootIndex = inorder.index(root.val)
root.left = self.buildTree(inorder[0:rootIndex], postorder[0:rootIndex])
root.right = self.buildTree(inorder[rootIndex+1:],postorder[rootIndex:-1])
return root
标签:inorder,self,51,rootIndex,二叉树,root,106,postorder 来源: https://blog.csdn.net/weixin_41362649/article/details/122760658