PTA 是否完全二叉搜索树

256 阅读2分钟

将一系列给定数字顺序插入一个初始为空的二叉搜索树(定义为左子树键值大,右子树键值小),你需要判断最后的树是否一棵完全二叉树,并且给出其层序遍历的结果。

输入格式:

输入第一行给出一个不超过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 <iostream>
#include <queue>
using namespace std;
typedef struct Node
{
    int Key;
    struct Node *L, *R;
} Node, *Tree;

void InsertNode(Tree &T, int e)
{
    if (!T)
    {
        T = new Node;
        T->Key = e;
        T->L = NULL;
        T->R = NULL;
    }
    else if (e > T->Key)
        InsertNode(T->L, e);
    else if (e < T->Key) 
        InsertNode(T->R, e);
}

void CreateTree(Tree &T, int a[], int n)
{
    T = NULL;
    for (int i = 0; i < n; i++)
    {
        InsertNode(T, a[i]);
    }
}
bool JudgeTree(Tree &T, int n)
{
    queue<Tree> Q;
    if (T == NULL)
        return true;
    else
    {
        int cnt = 0;
        Q.push(T);
        Tree t;
        while ((t = Q.front()) != NULL)
        {
            Q.push(t->L);
            Q.push(t->R);
            Q.pop();
            cnt++;
        }
        if (cnt == n)
            return true;
    }
    return false;
}

void PrintTree(Tree &T, int n)
{
    int i = 0;
    int data[21];
    queue<Tree> Q;
    Node *v;
    Q.push(T);
    while (!Q.empty())
    {
        v = Q.front();
        data[i++] = v->Key;
        if (v->L != NULL)
        {
            Q.push(v->L);
        }
        if (v->R != NULL)
        {
            Q.push(v->R);
        }
        Q.pop();
    }
    cout << data[0];
    for (int j = 1; j < n; j++)
    {
        cout << " " << data[j];
    }
    cout << endl;
}

int main()
{
    int n;
    cin >> n;
    int a[n]; 
    for (int i = 0; i < n; i++)
    {
        cin >> a[i];
    }
    Tree T;
    CreateTree(T, a, n);
    if (JudgeTree(T, n))
    {
        PrintTree(T, n);
        cout << "YES";
    }
    else
    {
        PrintTree(T, n);
        cout << "NO";
    }
}

提交结果:

屏幕截图 2021-11-29 154236.png