题解 | #重建二叉树#

重建二叉树

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

Divider and conquer with recursion:
for each tree, it is composed of three parts: root-left branch, right branch. each branch is also composed of root>left>right. so we could extend the root recursively by concatenating
its left and right node:

class Solution:
    # return the root of TreeNode
    def reConstructBinaryTree(self, pre, vin):
             # write code here
        if not pre or not vin:
            return None 
        self.hash_={}

        for i in range(len(vin)):
            self.hash_[vin[i]]=i
        root = TreeNode(pre[0])     
        # index is used in inorder list to slice the left and right brach based on current 
        # root or subroot; length_left is the length of left branch nodes, it is used in 
        # preorder list to slice the left and right branch based on the frist node of 
        # of updated preorder list is the current root (root or subroot)
        index=self.hash_[pre[0]]
        length_left = len(vin[:index])

        if index == 0:
            root.left = None
        else:
            root.left = self.reConstructBinaryTree(pre[1:length_left+1], vin[:index])
        if length_left + 1 < len(pre):
            root.right = self.reConstructBinaryTree(pre[length_left+1:], vin[index+1:])
        else:
            root.right = None
        return root
全部评论

相关推荐

09-08 17:17
同济大学 Java
狗不理fe:里面的人劝一句,别来虾,我们部门24校招生淘汰率30%,还有一些人说有一年保护期,不可能!!!
我的秋招日记
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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