PTA天梯赛L3-010 是否完全二叉搜索树【二叉树】

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

输入格式:

输入第一行给出一个不超过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<set>
#include<map>
#include<cstdio>
#include<cmath>
#include<queue>
#include<vector>
#include<string>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long ll;
const int inf = 0x3f3f3f3f;
const int maxn = 2e6 + 10;
int tree[maxn];

void add(int x, int v)
{
    if(tree[x] == -1)
    {
        tree[x] = v;
        return;
    }
    if(tree[x] < v)
        add(x * 2, v);
    else
        add(x * 2 + 1, v);
}

int main()
{
    memset(tree, -1, sizeof(tree));
    int n, x;
    cin >> n;
    for(int i = 0; i < n; ++i)
    {
        cin >> x;
        add(1, x);
    }
    bool flag = false;
    int num = 1 << n;
    for(int i = 1; i <= num; ++i)
    {
        if(i <= n && tree[i] == -1)
            flag = true;
        else if(tree[i] != -1)
        {
            if(i == 1)
                cout << tree[i];
            else
                cout << " " << tree[i];
        }
    }
    cout << endl;
    if(flag)
        cout << "NO";
    else
        cout << "YES";
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41785863/article/details/88650700
今日推荐