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
代码
class Solution:
def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:
if len(inorder)!=len(postorder) or len(inorder) == 0:
return None
if len(inorder) == 1:
return TreeNode(postorder[-1])
root = TreeNode(postorder[-1])
index = inorder.index(root.val)
root.left = self.buildTree(inorder[0:index], postorder[0:index])
root.right = self.buildTree(inorder[index+1:], postorder[index:-1])
return root
运行结果
Runtime: 216 ms, faster than 44.97% of Python3 online submissions for Construct Binary Tree from Inorder and Postorder Traversal.
Memory Usage: 87.6 MB, less than 8.55% of Python3 online submissions for Construct Binary Tree from Inorder and Postorder Traversal.