【leetcode】106. Construct Binary Tree from Inorder and Postorder Traversal

题目如下:

解题思路:本题是根据中序和后序来构建树,和【leetcode】105. Construct Binary Tree from Preorder and Inorder Traversal思路一样。只不过后序遍历的结果是根节点在后,所以依次取根节点的方法就是postorder.pop(-1),因为倒着取的,所以遍历的时候,需要先右后左。

代码如下:

# 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 traverse(self,parent,postorder,inorder,director):
        if len(postorder) == 0 or len(inorder) == 0:
            return
        node = TreeNode(postorder.pop(-1))
        if director == 'L':
            parent.left = node
        else:
            parent.right = node

        inx = inorder.index(node.val)
        self.traverse(node, postorder, inorder[inx + 1:], 'R')
        self.traverse(node, postorder, inorder[0:inx], 'L')

    def buildTree(self, inorder, postorder):
        """
        :type inorder: List[int]
        :type postorder: List[int]
        :rtype: TreeNode
        """
        if len(postorder) == 0 or len(inorder) == 0:
            return None
        root = TreeNode(postorder.pop(-1))
        inx = inorder.index(root.val)
        self.traverse(root,postorder,inorder[inx+1:],'R')
        self.traverse(root, postorder, inorder[0:inx], 'L')
        return root
        

 

posted @ 2018-09-17 10:14  seyjs  阅读(121)  评论(0编辑  收藏  举报