题目分析:
根据一棵树的中序遍历与后序遍历构造二叉树。注意:你可以假设树中没有重复的元素。
例如,给出中序遍历 inorder = [9,3,15,20,7],后序遍历 postorder = [9,15,7,20,3]。返回如下的二叉树:
解题思路:
这一题与105. Construct Binary Tree from Preorder and Inorder Traversal基本完全相同,可以参考上一个博客。
提交代码1:(简洁递归,时间复杂度O(N2),Runtime: 192 ms, faster than 40.77% )
class Solution:
def buildTree(self, inorder: 'List[int]', postorder: 'List[int]') -> TreeNode:
if not inorder: return None
root = TreeNode(postorder[-1])
index = inorder.index(postorder[-1])
root.left = self.buildTree(inorder[:index], postorder[:index])
root.right = self.buildTree(inorder[index+1:], postorder[index:-1])
return root
提交代码2:(使用字典不必每次切割数组的递归,切片的时间复杂度是O(N),使时间复杂度下降到O(N),Runtime: 80 ms, faster than 79.52% )
class Solution:
def buildTree(self, inorder: 'List[int]', postorder: 'List[int]') -> TreeNode:
inorder_map = {}
for i, val in enumerate(inorder): inorder_map[val] = i
def addNode(low, high):
if low > high: return None
root = TreeNode(postorder.pop())
index = inorder.index(root.val)
root.right = addNode(index + 1, high)
root.left = addNode(low, index - 1)
return root
return addNode(0, len(inorder) - 1)