美文网首页
2019-08-22剑指 重建二叉树

2019-08-22剑指 重建二叉树

作者: mztkenan | 来源:发表于2019-08-22 18:40 被阅读0次
class Solution:
    # 返回构造的TreeNode根节点
    def reConstructBinaryTree(self, pre, tin):
        if not pre or not tin:return None
        if len(pre)==1:return TreeNode(pre[0])
        root=pre[0]
        index=tin.index(root)
        l=self.reConstructBinaryTree(pre[1:index+1],tin[:index]) #if index+1<=len(pre) else None #这里可以省略
        r=self.reConstructBinaryTree(pre[index+1:],tin[index+1:])#if index+1<len(pre) else None # 这里可以省略
        root=TreeNode(root)
        root.left=l
        root.right=r
        return root

以下为错误代码

class Solution:
    # 返回构造的TreeNode根节点
    def reConstructBinaryTree(self, pre:List, tin:List):
        if not pre or not tin:return None
        if len(pre)==1:return TreeNode(pre[0])
        print(pre,tin)
        root=pre[0]
        index=tin.index(root)
        mid=pre.index(tin[:index][-1]) # [1, 2, 4, 3, 5, 6] [4, 2, 1, 5, 3, 6]这里出错了 ,2并不是左子树最后一个
        l=self.reConstructBinaryTree(pre[1:mid+1],tin[:index]) if mid+1<=len(pre) else None
        r=self.reConstructBinaryTree(pre[mid+1:],tin[index+1:])if mid+1<len(pre) else None # 这里+1别忘记
        root=TreeNode(root)
        root.left=l
        root.right=r
        return root

相关文章

  • LeetCode | 面试题07. 重建二叉树【剑指Offer】

    LeetCode 面试题07. 重建二叉树【剑指Offer】【Medium】【Python】【二叉树】【递归】 问...

  • 剑指Offer(四)

    剑指Offer(四) 重建二叉树 题目描述: 输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的...

  • 重建二叉树

    《剑指offer》面试题7:重建二叉树 题目:输入某二叉树的前序遍历和中序遍历的结果,请重建该二叉树。假设输入的前...

  • 71.重建二叉树

    day18: 剑指 Offer 07. 重建二叉树[https://leetcode-cn.com/prob...

  • 剑指Offer 07. 重建二叉树

    剑指 Offer 07. 重建二叉树 题目传送门[https://leetcode-cn.com/problems...

  • 重建二叉树

    上牛客网做了一道剑指offer的算法题 重建二叉树 输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设...

  • 2019-08-22剑指 重建二叉树

    以下为错误代码

  • 剑指Offer--(5)重建二叉树

    title: 剑指Offer--(5)重建二叉树 categories: 算法与数据结构 tags: 数据结构 题...

  • 剑指offer第二版-7.重建二叉树

    本系列导航:剑指offer(第二版)java实现导航帖 面试题7:重建二叉树 题目要求:根据二叉树的前序遍历和中序...

  • go 重建二叉树

    这是剑指offer的一道题。 输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍...

网友评论

      本文标题:2019-08-22剑指 重建二叉树

      本文链接:https://www.haomeiwen.com/subject/kzfosctx.html