根据一棵树的中序遍历与后序遍历构造二叉树。
中序遍历 inorder = [9,3,15,20,7]后序遍历 postorder = [9,15,7,20,3]
3 / \ 9 20 / \ 15 7
Python 实现
# Definition for a binary tree node.# class TreeNode(object):# def __init__(self, x):# self.val = x# self.left = None# self.right = Noneclass Solution(object): def buildTree(self, inorder, postorder): """ :type inorder: List[int] :type postorder: List[int] :rtype: TreeNode """ if not postorder or not inorder: return None; node = TreeNode(postorder[-1]) mid = inorder.index(postorder[-1]) node.left = self.buildTree(inorder[:mid],postorder[:mid]) node.right = self.buildTree(inorder[mid+1:],postorder[mid:-1]) return node