# 程序员面试50题（2）—二元查找树的后序遍历结果[数据结构]

8
/  \
6    10
/ \    / \
5   7   9  11

using namespace std;

///////////////////////////////////////////////////////////////////////
// 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);
}

posted @ 2016-06-16 13:22  Code~Rush  阅读(440)  评论(0编辑  收藏  举报