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

重建二叉树

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

Python解法:

前序遍历pre:中左右;中序遍历tin: 左中右
这个出错的点在于:
如果pre为空的时候,应该直接return None而不是return TreeNode(None)

class Solution:
    # 返回构造的TreeNode根节点
    def reConstructBinaryTree(self, pre, tin):
        # write code here
        # pre:中左右;tin: 左中右

        if len(pre) == 0:
            return None
        node = TreeNode(pre[0])
        index = tin.index(pre[0])
        node.left = self.reConstructBinaryTree(pre[1:index + 1], tin[:index])
        node.right = self.reConstructBinaryTree(pre[index + 1:], tin[index + 1:])
        return node
全部评论

相关推荐

在瑞幸干两年,奥特曼都得闪灯
不知名的牛友:奥特曼每天只上3分钟班
点赞 评论 收藏
分享
06-18 13:28
已编辑
门头沟学院 Web前端
爱睡觉的冰箱哥:《给予你300的工资》,阴的没边了
点赞 评论 收藏
分享
代码飞升:别用口语,后端就写后端,前端就写前端,最后别光后悔
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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