Skip to content

1110 Complete Binary Tree

Statement

Metadata

  • 作者: CHEN, Yue
  • 单位: 浙江大学
  • 代码长度限制: 16 KB
  • 时间限制: 400 ms
  • 内存限制: 64 MB

Given a tree, you are supposed to tell if it is a complete binary tree.

Input Specification

Each input file contains one test case. For each case, the first line gives a positive integer N (\le 20) which is the total number of nodes in the tree – and hence the nodes are numbered from 0 to N-1. Then N lines follow, each corresponds to a node, and gives the indices of the left and right children of the node. If the child does not exist, a - will be put at the position. Any pair of children are separated by a space.

Output Specification

For each case, print in one line YES and the index of the last node if the tree is a complete binary tree, or NO and the index of the root if not. There must be exactly one space separating the word and the number.

Sample Input 1

9
7 8
- -
- -
- -
0 1
2 3
4 5
- -
- -

Sample Output 1

YES 8

Sample Input 2

8
- -
4 5
0 6
- -
2 3
- 7
- -
- -

Sample Output 2

NO 1

Solution

#include <bits/stdc++.h>
using namespace std;
const int N = 1100;

struct E {
    int son[2];
    E() {
        son[0] = son[1] = -1;
    }
} e[N];

int n, Max, MaxId, vis[N];

void dfs(int u, int id) {
    MaxId = max(MaxId, id);
    if (id == n)
        Max = u;
    int now = e[u].son[0];
    if (now != -1)
        dfs(now, id << 1);
    now = e[u].son[1];
    if (now != -1)
        dfs(now, id << 1 | 1);
}

int main() {
    while (scanf("%d", &n) != EOF) {
        assert(n <= 20);
        memset(e, -1, sizeof e);
        memset(vis, 0, sizeof vis);
        for (int i = 0; i < n; ++i) {
            static char x[10], y[10];
            scanf("%s %s", x, y);
            if (x[0] != '-') {
                int c = 0;
                for (int j = 0; x[j]; ++j) c = c * 10 + x[j] - '0';
                e[i].son[0] = c;
                vis[c] = 1;
            }
            if (y[0] != '-') {
                int c = 0;
                for (int j = 0; y[j]; ++j) c = c * 10 + y[j] - '0';
                e[i].son[1] = c;
                vis[c] = 1;
            }
        }
        int rt = -1;
        for (int i = 0; i < n; ++i) {
            if (!vis[i]) {
                assert(rt == -1);
                rt = i;
            }
        }
        Max = -1;
        MaxId = 0;
        dfs(rt, 1);
        if (MaxId == n) {
            cout << "YES " << Max;
        } else {
            cout << "NO " << rt;
        }
        cout << "\n";
    }
    return 0;
}

Last update: May 4, 2022
Back to top