如题,递归方法与迭代方法。
两个关键点:一:后序遍历的最后一项是树的根节点,这个根节点在中序遍历的中间把中序遍历分成左子树和右子树两部分;二:同一个树中序遍历和后序遍历包含元素相同(顺序不同),通过中序遍历的分隔点返回后序遍历,找到左右子树的后序遍历。
两点注意事项:一个是小心笔误;第二个是找到根节点后,到中序遍历中找到分隔点,这个分隔点同样是后序遍历的分隔点。举例来说:
中序遍历: 【左子树部分】(分隔点)【根节点】【右子树部分】
后序遍历:【左子树部分】(分隔点)【右子树部分】【根节点】
最终我的迭代实现成绩:
执行用时 :92 ms, 在所有 Python 提交中击败了92.70% 的用户
内存消耗 :13.2 MB, 在所有 Python 提交中击败了98.79%的用户
代码如下:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# digui, time failed, 202/203
class Solution(object):
def buildTree(self, inorder, postorder):
"""
:type inorder: List[int]
:type postorder: List[int]
:rtype: TreeNode
"""
if len(inorder) == 0:
return None
if len(inorder) == 1:
return TreeNode(inorder[0])
# the last item of postorder must be the root!
root_value = postorder[-1]
return_node = TreeNode(root_value)
# split using root_value
split_index = inorder.index(root_value)
left_inorder = inorder[:split_index]
right_inorder = inorder[split_index + 1:]
# !
left_postorder = postorder[:split_index]
right_postorder = postorder[split_index:-1]
return_node.left = self.buildTree(left_inorder, left_postorder)
return_node.right = self.buildTree(right_inorder, right_postorder)
return return_node
# diedai
class Solution(object):
def buildTree(self, inorder, postorder):
"""
:type inorder: List[int]
:type postorder: List[int]
:rtype: TreeNode
"""
if len(postorder) == 0:
return None
return_node = TreeNode(postorder[-1])
current_level = [return_node]
current_inorder = [inorder]
current_postorder = [postorder]
while(len(current_level)):
new_level = []
new_inorder = []
new_postorder = []
for i, current_node in enumerate(current_level):
inorder = current_inorder[i]
postorder = current_postorder[i]
current_node_value = current_node.val
split_index = inorder.index(current_node_value)
left_inorder = inorder[:split_index]
right_inorder = inorder[split_index + 1:]
# !
left_postorder = postorder[:split_index]
right_postorder = postorder[split_index:-1]
if len(left_postorder):
current_node.left = TreeNode(left_postorder[-1])
new_level.append(current_node.left)
new_inorder.append(left_inorder)
new_postorder.append(left_postorder)
if len(right_postorder):
current_node.right = TreeNode(right_postorder[-1])
new_level.append(current_node.right)
new_inorder.append(right_inorder)
new_postorder.append(right_postorder)
current_level = new_level
current_inorder = new_inorder
current_postorder = new_postorder
return return_node