已知后序遍历和中序遍历重建二叉树和已知前序遍历和中序遍历求后序遍历的时候已经说明思路,这里直接贴代码
# -*- coding:utf-8 -*-
class Solution(object):
def reConstructBinaryTree(self, post, mid):
if len(post) == 0 or len(mid) == 0:
return None
# 把头结点放入列表中
li = [post[-1],]
# 在中序遍历中找到根节点的位置
i = mid.index(post[-1])
# 遍历左子树
root_left = self.reConstructBinaryTree(post[0 : i], mid[0 : i])
# 遍历右子树
root_right = self.reConstructBinaryTree(post[i : -1], mid[i + 1 : ])
# 把所得到的结点连接,把返回结果为空的情况剔除
if root_left is not None and root_right is not None:
# 注意这两个值的连接顺序(和已知前序和中序相反)
li.extend(root_left)
li.extend(root_right)
elif root_left is not None:
li.extend(root_left)
elif root_right is not None:
li.extend(root_right)
return li
if __name__ == "__main__":
a = Solution()
post_order = [7, 4, 2, 5, 8, 6, 3, 1] # 后序遍历
mid_order = [4, 7, 2, 1, 5, 3, 8, 6] # 中序遍历
print a.reConstructBinaryTree(post_order, mid_order)