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

重建二叉树

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
全部评论

相关推荐

不愿透露姓名的神秘牛友
05-28 12:15
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
06-24 20:25
腾讯今年实习招了这么多人,后面秋招还会招人吗??想着秋招再战来着
牛客96559368...:腾讯好像2020年之后就是实习生招得多,应届生基本上不招,纯实习转正
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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