【剑指offer】面试题24:二叉搜索树的兴许前序遍历序列

分析:

前序: 根 左 右

后序: 左 由 根

二叉搜索树: 左 < 根 < 右

那么这就非常明显了。

def ifpost(postArray, start, end):
	#one or "" is true
	if(end - start <= 1):
		return True
	i = start
	#left branch whose value < root
	while i <= end and postArray[i] < postArray[end]:
		i += 1
	#partion of left and right branch
	part = i
	#right branch whose value > root
	while i <= end and postArray[i] > postArray[end]:
		i += 1
	#not all right part > root
	if(i < end):
		return False
	return ifpost(postArray, start, part - 1) and ifpost(postArray, part, end - 1)

def ifpreorder(preArray, start, end):
	if(end - start <= 1):
		return True
	i = end
	while(i >= start and preArray[i] > preArray[start]):
		i -= 1
	partition = i
	while(i >= start and preArray[i] < preArray[start]):
		i -= 1
	if(i > start):
		return False
	return ifpreorder(preArray, start + 1, partition) and \
	 ifpreorder(preArray, partition + 1, end)


posted @ 2014-08-26 20:52  mengfanrong  阅读(194)  评论(0)    收藏  举报
众安尊享e升2025版 - 底部横幅广告
尊享e升 2025版
🚀 全新升级
百万医疗险全面升级 守护健康人生
✓ 一般医疗300万
✓ 重疾600万
✓ 6年保证续保
✓ 1万免赔额
600万
最高保障
首月特惠价
低至1元起
🛡️ 立即投保