1. 程式人生 > >7-2 是否完全二叉搜尋樹 (30 分)

7-2 是否完全二叉搜尋樹 (30 分)

將一系列給定數字順序插入一個初始為空的二叉搜尋樹(定義為左子樹鍵值大,右子樹鍵值小),你需要判斷最後的樹是否一棵完全二叉樹,並且給出其層序遍歷的結果。

輸入格式:

輸入第一行給出一個不超過20的正整數N;第二行給出N個互不相同的正整數,其間以空格分隔。

輸出格式:

將輸入的N個正整數順序插入一個初始為空的二叉搜尋樹。在第一行中輸出結果樹的層序遍歷結果,數字間以1個空格分隔,行的首尾不得有多餘空格。第二行輸出YES,如果該樹是完全二叉樹;否則輸出NO

輸入樣例1:

9
38 45 42 24 58 30 67 12 51

輸出樣例1:

38 45 24 58 42 30 12 67 51
YES

輸入樣例2:

8
38 24 12 45 58 67 42 51

輸出樣例2:

38 45 24 58 42 12 67 51
NO
#include <bits/stdc++.h>
using namespace std;
bool f=true,exs=false;
typedef struct BNode *BinTree;
struct BNode
{
    int data;
    BinTree left;
    BinTree right;
};
void Insert(BinTree &t,int e){
    if(!t){
        t=(BinTree)malloc(sizeof(BNode));
        t->left=t->right=NULL;
        t->data=e;
    }
    else if(e>t->data){
        Insert(t->left,e);
    }
    else if(e<t->data){
        Insert(t->right,e);
    }
}
void Print(BinTree t){
    queue<BinTree>q;
    q.push(t);
    int is=0;
    while(!q.empty()){
        BinTree temp=q.front();
        q.pop();
        if(is)cout<<" ";
        else is++;
        cout<<temp->data;
        if(temp->left&&temp->right){
            q.push(temp->left);
            q.push(temp->right);
            if(exs)f=false;
        }
        else if(temp->left&&!temp->right){
            q.push(temp->left);
            exs=true;
        }
        else if(temp->right&&!temp->left){
            q.push(temp->right);
            f=false;
        }
        else if(!temp->left&&!temp->right)exs=true;
    }
    cout<<endl;
    if(f)cout<<"YES"<<endl;
    else cout<<"NO"<<endl;
}
int main()
{
    int n,a;
    BinTree t=NULL;
    cin>>n;
    for(int i=0;i<n;i++){
        cin>>a;
        Insert(t,a);
    }
    Print(t);
}