标签:roo pre tor val leetcode img build elf 后序
题目描述:
方法一:O(n) O(n)
class Solution: def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode: assert len(inorder)==len(postorder) if len(inorder)==0: return None if len(inorder)==1: return TreeNode(inorder[0]) pos = inorder.index(postorder[-1]) root = TreeNode(postorder[-1]) root.left = self.buildTree(inorder[:pos],postorder[:pos]) root.right = self.buildTree(inorder[pos+1:],postorder[pos:-1]) return root
方法二;
class Solution: def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode: d={j:i for i,j in enumerate(inorder)} def f(i,j): if i<j: t=TreeNode(postorder.pop()) t.right=f(d[t.val]+1,j) t.left=f(i,d[t.val]) return t return f(0,len(inorder))
标签:roo pre tor val leetcode img build elf 后序
原文地址:https://www.cnblogs.com/oldby/p/11184943.html