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;
}
上一篇:Docker容期卷安装MySQL


下一篇:springboot整合hive-jdbc遇到的坑