重建二叉树

重建二叉树

http://www.nowcoder.com/questionTerminal/8a19cbe657394eeaac2f6ea9b0f6fcf6

思路:

递归并正确分割前序和中序序列
前序分割为左子树和右子树,左子树的开头是第二个数,中间包含节点的数量为中序从0到根节点的数量
所以是pre[1:tin.index(pre[0])+1]
右子树是剩下的部分

同理,中序左子树是从左边到根节点的部分,tin[:tin.index(pre[0])]

递归

     def reConstructBinaryTree(self, pre, tin):
        # write code here
        if len(pre)==0:
            return None
        if len(pre)==1:
            return TreeNode(pre[0])
        root=TreeNode(pre[0])
        tinL=tin[:tin.index(pre[0])]
        tinR=tin[tin.index(pre[0])+1:]
        root.left=self.reConstructBinaryTree(pre[1:tin.index(pre[0])+1],tinL)
        root.right=self.reConstructBinaryTree(pre[tin.index(pre[0])+1:],tinR)
        return root
全部评论
我也这样写的,为啥不通过
点赞 回复 分享
发布于 2020-03-31 23:33
第二个if 语句可以去掉。没影响。
点赞 回复 分享
发布于 2020-02-11 10:43

相关推荐

05-25 10:45
西华大学 Java
Frank_zhang:没实习一个项目肯定不够,可以再做一个轮子,技术栈再补一个mq,微服务,整体再换个简历模板,暑期尽量再找一个日常实习
点赞 评论 收藏
分享
评论
16
收藏
分享

创作者周榜

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