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

重建二叉树

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

相关推荐

这是什么操作什么意思,这公司我服了...
斯派克spark:意思是有比你更便宜的牛马了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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