判斷整數序列是不是二元查找樹的後序遍歷結果

題目:輸入一個整數數組,判斷該數組是不是某二元查找樹的後序遍歷的結果。如果是返回true,否則返回false。
例如輸入5、7、6、9、11、10、8,由於這一整數序列是如下樹的後序遍歷結果:
8 / \ 6 10 / \ / \ 5 7 9 11
因此返回true。
如果輸入7、4、6、5,沒有哪棵樹的後序遍歷的結果是這個序列,因此返回false。
// Verify whether a squence of integers are the post order traversal 
// of a binary search tree (BST)
// Input: squence - the squence of integers 
// length - the length of squence 
// Return: return ture if the squence is traversal result of a BST, 
// otherwise, return false 
bool verifySquenceOfBST(int squence[], int length) 
{ 
	if(squence == NULL || length <= 0) 
		return false; 
	// root of a BST is at the end of post order traversal squence 
	int root = squence[length - 1]; // the nodes in left sub-tree are less than the root 
	int i = 0; 
	for(; i < length - 1; ++ i) 
	{ 
		if(squence[i] > root) 
			break; 
	} // the nodes in the right sub-tree are greater than the root 
	int j = i; 
	for(; j < length - 1; ++ j) 
	{ 
		if(squence[j] < root) 
			return false; 
	} // verify whether the left sub-tree is a BST 
	bool left = true; 
	if(i > 0) 
		left = verifySquenceOfBST(squence, i); // verify whether the right sub-tree is a BST 
	bool right = true; 
	if(i < length - 1) 
		right = verifySquenceOfBST(squence + i, length - i - 1); 
	return (left && right); 
}

發佈了64 篇原創文章 · 獲贊 11 · 訪問量 14萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章