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

全部评论

相关推荐

点赞 评论 收藏
分享
10-30 19:23
已编辑
山东大学(威海) C++
牛至超人:其实简历是不需要事无巨细的写的,让对方知道你有这段经历就行了,最重要的是面试的时候讲细讲明白
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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