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

2019-12-24  本文已影响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

上一篇下一篇

猜你喜欢

热点阅读