L3-010 是否完全二叉搜索树

题目链接

思路:
插入数据建立二搜索树,再用bfs获取二叉树的层序遍历,
再判断二叉完全:遍历tree数组1 ~ n若有点值为-1则代表不是完全二叉树。

代码:

#include <bits/stdc++.h>
#define fastio ios::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL)
#define debug(a) cout << "debug : " << (#a) << " = " << a << endl
#define lson idx << 1
#define rson idx << 1 | 1

using namespace std;

typedef long long ll;
typedef pair<int, int> PII;

const int N = 10010;
const int INF = 0x3f3f3f3f;
const double eps = 1e-6;
const int mod = 998244353;

int n;
int a[N];    //存输入序列
int tree[N]; //只存值
void Build()
{
    memset(tree, -1, sizeof tree);
    tree[1] = a[1];              //第一个数为根节点
    for (int i = 2; i <= n; i++) //插入剩下的n-1个到树中
    {
        int k = a[i];           //此时插入的值为k
        int idx = 1;            //初始化插入节点为根节点
        while (tree[idx] != -1) //循环查找符合要求的插入点
        {
            if (tree[idx] > k) //当插入值小于此节点值则为右子树
                idx = rson;
            else
                idx = lson;
        }
        tree[idx] = k;
    }
}
bool flag = true;
vector<int> tier;

void bfs_tier()
{
    queue<int> q;
    q.push(1);
    while (q.size())
    {
        int t = q.front();
        q.pop();
        int idx = t;
        tier.push_back(tree[idx]);
        if (tree[lson] != -1)
            q.push(lson);
        if (tree[rson] != -1)
            q.push(rson);
    }
}

int main()
{
    cin >> n;
    for (int i = 1; i <= n; i++)
        cin >> a[i];
    Build();
    bfs_tier();
    for (int i = 0; i < tier.size(); i++)
    {
        if (i != 0)
            cout << ' ';
        cout << tier[i];
    }
    cout << endl;
    for (int i = 1; i <= n; i++)
        if (tree[i] == -1)
        {
            flag = false;
            break;
        }
    if (flag)
        cout << "YES" << endl;
    else
        cout << "NO" << endl;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值