UESTC 483 Data Structure Problem (二叉樹)

題意:有T個樣例,每個樣例第一行表示有n個結點,第二行按照層次遍歷的順序依次給出每個結點的值,你需要判斷所給的二叉樹是堆還是二叉搜索樹

代碼如下:

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
int n;
int node[1000+10];
int chi[1000][2];
bool bst1(int i)
{
    if(!chi[i][0]&&!chi[i][1]) return true;
    bool key=true;
    if(chi[i][0]&&node[2*i]>node[i])   key=false;
    if(chi[i][1]&&node[2*i+1]<node[i]) key=false;
    return key&&bst1(2*i)&&bst1(2*i+1);
}
bool bst2(int i)
{
    if(!chi[i][0]&&!chi[i][1]) return true;
    bool key=true;
    if(chi[i][0]&&node[2*i]<node[i]) key=false;
    if(chi[i][1]&&node[2*i+1]>node[i]) key=false;
    return key&&bst2(2*i)&&bst2(2*i+1);
}
bool hea1(int i)
{
    if(!chi[i][0]&&!chi[i][1]) return true;
    bool key=true;
    if(chi[i][0]&&node[2*i]<node[i]) key=false;
    if(chi[i][1]&&node[2*i+1]<node[i]) key=false;
    return key&&hea1(2*i)&&hea1(2*i+1);
}
bool hea2(int i)
{
    if(!chi[i][0]&&!chi[i][1]) return true;
    bool key=true;
    if(chi[i][0]&&node[2*i]>node[i]) key=false;
    if(chi[i][1]&&node[2*i+1]>node[i]) key=false;
    return key&&hea2(2*i)&&hea2(2*i+1);
}
int main()
{
    int T;
    cin>>T;
    for(int cases=1;cases<=T;cases++)
    {
        memset(chi,0,sizeof(chi));
        cin>>n;
        cin>>node[1];
        for(int i=2;i<=n;i++)
        {
            cin>>node[i];
            chi[i/2][i%2]=1;
        }
        bool b=bst1(1)||bst2(1);
        bool h=hea1(1)||hea2(1);
        cout<<"Case #"<<cases<<": ";
        if(b&&h) cout<<"Both"<<endl;
        else if(b&&!h) cout<<"BST"<<endl;
        else if(!b&&h) cout<<"Heap"<<endl;
        else cout<<"Neither"<<endl;
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章