MS100(9)-判断整数序列是不是二元查找树的后序遍历结果

来源:互联网 发布:少儿围棋对弈软件 编辑:程序博客网 时间:2024/05/04 18:16
#include <iostream>
using namespace std;
 
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);
}
 
int main(void)
{
    int len,s[100];
    while (cin>>len)
    {
        for(int i=0;i<len;i++)
            cin>>s[i];
        if(verifySquenceOfBST(s,len))
            cout<<"ok!"<<endl;
        else
            cout<<"false!"<<endl;
    }
    return 0;
}
原创粉丝点击