非常有意思的一道题
Given two integer arrays inorder
and postorder
where inorder
is the inorder traversal of a binary tree and postorder
is the postorder traversal of the same tree, construct and return the binary tree.
Example 1:
Input: inorder = [9,3,15,20,7], postorder = [9,15,7,20,3] Output: [3,9,20,null,null,15,7]
Example 2:
Input: inorder = [-1], postorder = [-1] Output: [-1]
Constraints:
1 <= inorder.length <= 3000
postorder.length == inorder.length
-3000 <= inorder[i], postorder[i] <= 3000
inorder
andpostorder
consist of unique values.- Each value of
postorder
also appears ininorder
. inorder
is guaranteed to be the inorder traversal of the tree.postorder
is guaranteed to be the postorder traversal of the tree.
重点是元素互不重复
class Solution:
def buildTree(self, inorder, postorder):
if not postorder:
return None
root = TreeNode()
root.val = postorder[-1]
if len(postorder) == 1:
root.left = None
root.right = None
return root
else:
idx = inorder.index(root.val)
l_inorder = inorder[:idx]
r_inorder = inorder[idx+1:]
l_postorder = postorder[:idx]
r_postorder = postorder[idx:-1]
root.left = self.buildTree(l_inorder,l_postorder)
root.right = self.buildTree(r_inorder,r_postorder)
return root