日野弥生:勉強しよう

LeetCode 106 - 从中序与后序遍历序列构造二叉树

发表于2025年02月20日

#树 #二叉树 #数组 #哈希 #分治

本题的关键是要想明白:

class Solution:
    def buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]:
        # 列表均不能为空
        if not inorder or not postorder:
            return None
        # 先处理根节点
        root = TreeNode(postorder[-1], None, None)
        # 找到根结点的相对位置
        rootIndex = inorder.index(root.val)
        # 中序和后序中存储的左子树的长度一定是一样的
        root.left = self.buildTree(inorder[:rootIndex], postorder[:rootIndex])
        # python切片是前闭后开的
        root.right = self.buildTree(inorder[rootIndex + 1:],postorder[rootIndex:-1])

        return root

本题的list的index()函数效率不高,可以考虑用基于哈希技术的字典代替。

フラッシュタブ:LeetCode

题目链接:https://leetcode.cn/problems/construct-binary-tree-from-inorder-and-postorder-traversal/

上一篇

LeetCode 112 - 路径总和

下一篇

LeetCode 105 - 从前序与中序遍历序列构造二叉树