Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
For example, given
inorder = [9,3,15,20,7]
postorder = [9,15,7,20,3]
Return the following binary tree:
3
/ \
9 20
/ \
15 7
这个题目思路跟[LeetCode] 105. Construct Binary Tree from Preorder and Inorder Traversal_Medium tag: Tree Traversal一样, 只是root是postorder[-1], 而inorder[0] 而已, 本质一样.
Code:
class Solution:
def buildTree(self, postorder, inorder):
if not postorder or not inorder: return
root, index = TreeNode(postorder[-1]), inorder.index(postorder[-1])
root.left = self.buildTree(postorder[:index], inorder[:index])
root.right = self.buildTree(postorder[index: -1], inorder[index+1:])
return root