106. 从中序与后序遍历序列构造二叉树

python

这里使用了 list.index(), 这个非常有用

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def buildTree(self, inorder, postorder):
        """
        :type inorder: List[int]
        :type postorder: List[int]
        :rtype: TreeNode
        """
        # guard
        if len(inorder) ==0:
            return None
        
        root = TreeNode(postorder.pop(-1))
        
        if len(postorder)>0:
            left_in = inorder[:inorder.index(root.val)]
            right_in = inorder[inorder.index(root.val)+1:]
            if(len(left_in)>0):
                left_post = postorder[:len(left_in)]
                root.left = self.buildTree(left_in,left_post)
            if(len(right_in)>0):
                right_post = postorder[len(left_in):]
                root.right = self.buildTree(right_in, right_post)
        
        return root
        
    原文作者:cptn3m0
    原文地址: https://www.jianshu.com/p/4eba3129c382
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞