题解 | #重建二叉树#

重建二叉树

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

用python要比C++简单,因为截取数组方便,且最后在索引不对时直接返回None,然后返回空恰好又是没有左子树或者说右子树的情况。

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    # 返回构造的TreeNode根节点
    def reConstructBinaryTree(self, pre, tin):
        # write code here
        if not pre:
            return None
        # 根节点
        root = TreeNode(pre[0])
        # 根节点在中序遍历中的位置索引
        index = tin.index(pre[0])
        # 递归 构造树的左子树
        root.left = self.reConstructBinaryTree(pre[1:index+1], tin[:index])
        # 递归构造树的右子树
        root.right = self.reConstructBinaryTree(pre[index+1:], tin[index+1:])
        return root
        # write code here
算法解析 文章被收录于专栏

这里主要是算法岗的自我思路总结

全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务