Construct Binary Tree from Inorder and Postorder

题目描述

Given inorder and postorder traversal of a tree, construct the binary tree.

Note: You may assume that duplicates do not exist in the tree.

解题方法

Solution

递归

过不了leetcode OJ

# 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
        """
        if not postorder or not inorder:
            return 
        root = TreeNode(postorder[-1])
        indexIn = inorder.index(root.val)
        root.left = self.buildTree(inorder[:indexIn], postorder[:indexIn])
        root.right = self.buildTree(inorder[indexIn+1:], postorder[indexIn:len(postorder)-1])
        return root

Reference