美文网首页
根据中序与后续遍历序列构建二叉树

根据中序与后续遍历序列构建二叉树

作者: 而立之年的技术控 | 来源:发表于2019-12-24 23:39 被阅读0次

话不多说,送分题!核心:找根(可以去类比一下先序、中序找根!)

WechatIMG26.jpeg
class Solution:
    def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:
        if not inorder or not postorder:
            return None
        
        val = postorder[-1]
        root = TreeNode(val)
        
        index =  inorder.index(val)

        left = self.buildTree(inorder[:index], postorder[:index])
        right = self.buildTree(inorder[index+1:], postorder[index:-1])

        root.left = left
        root.right = right
        return root

相关文章

网友评论

      本文标题:根据中序与后续遍历序列构建二叉树

      本文链接:https://www.haomeiwen.com/subject/csjqoctx.html