LeetCode

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

2019-04-05  本文已影响0人  cptn3m0

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
        
上一篇下一篇

猜你喜欢

热点阅读