A1110 1110 Complete Binary Tree (25 point(s))

二叉树的建立,完全二叉树判断

1. 原文

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 (≤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:

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

Sample output 1:

1
YES 8

Sample Input 2:

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

Sample output 2:

1
NO 1

2. 解析

  • 查找根

    入度为0,indegree[i]

  • 层序判断

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
     if (v[temp].lchild!=-1)
    {
    q.push(v[temp].lchild);
    if (flag==1)
    {
    complete=false;
    }
    }else{
    flag=1;
    }

3. AC代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#include<cstdio>
#include<queue>
using namespace std;
char c1[5],c2[5];
struct node
{
int lchild,rchild;
}v[30];
int getnum(char c[])
{
int sum=0;
for (int i = 0; c[i] != '\0'; ++i)
{
sum=sum*10+c[i]-'0';
}
return sum;
}
int indegree[30]={};
int main()
{
int n;
scanf("%d",&n);
for (int i = 0; i < n; ++i)
{
scanf("%s%s",c1,c2);
if (c1[0]=='-')
{
v[i].lchild=-1;
}else{
v[i].lchild=getnum(c1);
indegree[getnum(c1)]++;
}
if (c2[0]=='-')
{
v[i].rchild=-1;
}else{
v[i].rchild=getnum(c2);
indegree[getnum(c2)]++;
}
}
int root=0;
for (int i = 0; i < n; ++i)
{
if (indegree[i]==0)
{
root=i;
break;
}
}
int flag=0;
bool complete=true;
queue<int> q;
q.push(root);
int last=0;
while(!q.empty()){
int temp=q.front();
last=temp;
q.pop();
if (v[temp].lchild!=-1)
{
q.push(v[temp].lchild);
if (flag==1)
{
complete=false;
}
}else{
flag=1;
}
if (v[temp].rchild!=-1)
{
q.push(v[temp].rchild);
if (flag==1)
{
complete=false;
}
}else{
flag=1;
}
}
if (complete)
{
printf("YES %d\n",last);
}else{
printf("NO %d\n",root);
}

return 0;
}
本文结束  感谢您的阅读
  • 本文作者: Wang Ting
  • 本文链接: /zh-CN/2019/09/03/A1110/
  • 发布时间: 2019-09-03 12:30
  • 更新时间: 2021-10-29 14:08
  • 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!