题解 | #重建二叉树#

重建二叉树

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

思路:先序遍历首位为根,然后基于根在中序遍历中拆分左、右子树,依次递归构建

注意:

1、root:1

2、idx:vin[root.val]

3、len(left) = [:idx]

4、len(right) = [idx+1:]

class Solution:
    def reConstructBinaryTree(self , pre: List[int], vin: List[int]) -> TreeNode:
        
        if len(pre) == 0 and len(vin) == 0:
            return
        
        root = TreeNode(pre[0])
        idx = vin.index(root.val)
        
        left = self.reConstructBinaryTree(pre[1:1+idx], vin[:idx])
        right = self.reConstructBinaryTree(pre[1+idx:], vin[idx+1:])
        root.left = left
        root.right = right
        
        return root
全部评论

相关推荐

03-29 12:10
门头沟学院 C++
挣K存W养DOG:散漫消极者淘汰,一眼坑爹。实习几个月转正的时候说你加班太少,能力还行态度不够积极裁了,马上老实。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务