美文网首页
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
    

    相关文章

      网友评论

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

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