原題地址:http://oj.leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/
題意:根據二叉樹的中序遍歷和后序遍歷恢復二叉樹。
解題思路:看到樹首先想到要用遞歸來解題。以這道題為例:如果一顆二叉樹為{1,2,3,4,5,6,7},則中序遍歷為{4,2,5,1,6,3,7},后序遍歷為{4,5,2,6,7,3,1},我們可以反推回去。由於后序遍歷的最后一個節點就是樹的根。也就是root=1,然后我們在中序遍歷中搜索1,可以看到中序遍歷的第四個數是1,也就是root。根據中序遍歷的定義,1左邊的數{4,2,5}就是左子樹的中序遍歷,1右邊的數{6,3,7}就是右子樹的中序遍歷。而對於后序遍歷來講,一定是先后序遍歷完左子樹,再后序遍歷完右子樹,最后遍歷根。於是可以推出:{4,5,2}就是左子樹的后序遍歷,{6,3,7}就是右子樹的后序遍歷。而我們已經知道{4,2,5}就是左子樹的中序遍歷,{6,3,7}就是右子樹的中序遍歷。再進行遞歸就可以解決問題了。
代碼:
# Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param inorder, a list of integers # @param postorder, a list of integers # @return a tree node def buildTree(self, inorder, postorder): if len(inorder) == 0: return None if len(inorder) == 1: return TreeNode(inorder[0]) root = TreeNode(postorder[len(postorder) - 1]) index = inorder.index(postorder[len(postorder) - 1]) root.left = self.buildTree(inorder[ 0 : index ], postorder[ 0 : index ]) root.right = self.buildTree(inorder[ index + 1 : len(inorder) ], postorder[ index : len(postorder) - 1 ]) return root
