题解 | #从中序与后序遍历序列构造二叉树# 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

全部评论

相关推荐

03-18 09:57
已编辑
重庆邮电大学 C++
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
03-20 12:46
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务