1. 程式人生 > >已知二叉樹的後序遍歷和中序遍歷求前序遍歷(二叉樹)

已知二叉樹的後序遍歷和中序遍歷求前序遍歷(二叉樹)

已知後序遍歷和中序遍歷重建二叉樹和已知前序遍歷和中序遍歷求後序遍歷的時候已經說明思路,這裡直接貼程式碼

# -*- 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)