0
点赞
收藏
分享

微信扫一扫

LC: 剑指 Offer 07. 重建二叉树

柠檬果然酸 2022-04-29 阅读 32
python

题目:

剑指 Offer 07. 重建二叉树。

输入某二叉树的前序遍历和中序遍历的结果,请构建该二叉树并返回其根节点。

假设输入的前序遍历和中序遍历的结果中都不含重复的数字。

链接:https://leetcode-cn.com/leetbook/read/illustrate-lcof/9mq1xr/

本题与主站 105 题重复:https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/

示例:

在这里插入图片描述

限制: 0 <= 节点个数 <= 5000

思路:

整体思路:先由前序遍历结果确定根节点,再由中序遍历结果确定左右节点。

算法流程:

遍历中序遍历结果,生成值与索引的映射字典。调用递归函数。

递归参数:前序遍历中的根节点,中序遍历左边界,中序遍历右边界;

终止条件:当左边界大于右边界,说明子树中序遍历结果为空;

递归内容:由前序遍历确定根节点,根据映射字典确定根节点在中序遍历结果中的索引值,通过所以索引值确定左右子树中序遍历的边界。

代码:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
        self.preorder = preorder
        self.mapping = {inorder[i]: i for i in range(len(preorder))}
        return self.build(0, 0 , len(inorder)-1)

    def build(self, preroot_index, left_index, right_index):
        if left_index > right_index:
            return
        root = TreeNode(self.preorder[preroot_index])
        inroot_index = self.mapping[self.preorder[preroot_index]]
        root.left = self.build(preroot_index+1, left_index, inroot_index-1)
        root.right = self.build(preroot_index+inroot_index-left_index+1, inroot_index+1, right_index)
        return root

时间复杂度O(n),空间复杂度O(n).

举报

相关推荐

0 条评论