1110 Complete Binary Tree (25 分)

判断一棵二叉树是不是完全二叉树,这个感觉用层序遍历比较合适,然后就是层序遍历里面的分类讨论,如果这个节点有右儿子没有左儿子,那么直接返回,同理,直接向下分类讨论,设立了两个标记变量,讨论输出即可

看了别人的解法,判断-1是不是提前出现,是一个比较简单的判断方法

#include <bits/stdc++.h>

#define fi first
#define se second
#define pb push_back
#define all(x) (x).begin(), (x).end()

using namespace std;

typedef long long ll;
typedef vector<int> vi;
typedef pair<int, int> pa;

struct node {
    int lchild, rchild;
} tree[25];

int ok, check, last;
int Hash[25];

void layerorder(int root) {
    queue<int> q;
    q.push(root);
    while (!q.empty()) {
        int now = q.front(); q.pop();
        last = now;
        int l = tree[now].lchild;
        int r = tree[now].rchild;
        if (l == -1 && r != -1) { check = 1; return; }
        if (l != -1 && r != -1) {
            if (ok) { check = 1; return; }
        } else {
            if (ok == 0) ok = 1;
            else {
                if (l != -1 && r == -1) { check = 1; return; }
            }
        }
        if (l != -1) q.push(l);
        if (r != -1) q.push(r);
    }
}

int main() {
    int n;
    cin >> n;
    for (int i = 0; i < n; i++) {
        string s1, s2;
        cin >> s1 >> s2;
        if (s1 == "-") tree[i].lchild = -1;
        else { tree[i].lchild = stoi(s1); Hash[stoi(s1)] = 1; }
        if (s2 == "-") tree[i].rchild = -1;
        else { tree[i].rchild = stoi(s2); Hash[stoi(s2)] = 1; }
    }
    int root;
    for (int i = 0; i < n; i++) if (!Hash[i]) root = i;
    layerorder(root);
    if (check) cout << "NO " << root;
    else cout << "YES " << last;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值