话不多说,送分题!核心:找根(可以去类比一下先序、中序找根!)
class Solution:
def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:
if not inorder or not postorder:
return None
val = postorder[-1]
root = TreeNode(val)
index = inorder.index(val)
left = self.buildTree(inorder[:index], postorder[:index])
right = self.buildTree(inorder[index+1:], postorder[index:-1])
root.left = left
root.right = right
return root