Construct Binary Tree from Inorder and Postorder Traversal
思路和依据前序遍历和中序遍历重建树的思路一样,复杂度也一致,代码如下:
class Solution(object): def buildTree(self, inorder, postorder): """ :type inorder: List[int] :type postorder: List[int] :rtype: TreeNode """ if not inorder: return None length = len(inorder) map = {} for i in xrange(length): map[inorder[i]] = i return self.helper(postorder,0,length-1,0,length-1,map) def helper(self,postorder,Istart,Iend,Pstart,Pend,map): if Istart > Iend: return None node = TreeNode(postorder[Pend]) if Istart == Iend: return node index = map[node.val] node.left = self.helper(postorder,Istart,index-1, Pstart,Pstart+index-Istart-1,map) node.right = self.helper(postorder,index+1,Iend,Pstart+index-Istart,Pend-1,map) return node
posted on 2016-04-18 20:14 Sheryl Wang 阅读(146) 评论(0) 编辑 收藏 举报