1110 Complete Binary Tree (25 分)
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:
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
说实话,这道题本身不难做,但是输入数据处理不容易。我先是准备用scanf,发现这么久没用了,特殊字符的输入已经不会了,所以只能换回去。但是忘了题目限制N<25,则可能有节点标号为两位数,没考虑到,按全个位数处理的,结果bug老是改不成,最后看的别人的博客才发现问题。
思路比较容易,先是输入建树,找到没有在叶节点出现过的节点即为根节点,之后对整棵树进行层次遍历,此时有两种判断是否是完全二叉树的方法:
- 法一:当遍历到一个空节点+非空节点的前后次序时,则非完全二叉树。当把队列中所有节点都遍历完都没出现上述次序是,则为完全二叉树。这可以设置一个标志位实现,不麻烦。
- 法二:每次节点非空则cnt++,遍历到第一个空节点时,如果此时cnt==n,则说明所有非空节点都已被遍历到,说明这是一个完全二叉树;否则,不是一棵完全二叉树。这个方法用的多。
另,这道题用顺序树更好做,见其他大神们的博客,我却用了最常用的二叉链表。以后碰到稍微难处理一点的输入输出,就用流吧,我C的处理方法几乎全忘光了,当时就没搞太明白。
#include <bits/stdc++.h>
#define N 105
using namespace std;
bool lo[N];
typedef pair<int,int> pii;
typedef struct bt{
int data;
bt *lc,*rc;
}bt;
vector<pii> vpi;
queue<bt*> qb;
int last,n,root,a,b;
bt* buildTree(int root) {
if (root==-1) return nullptr;
bt* nw=new bt;
nw->data=root;
nw->lc=buildTree(vpi[root].first);
nw->rc=buildTree(vpi[root].second);
return nw;
}
void levelTraversal(bt* tr) {
if (tr==nullptr) return;
int cnt=0;
qb.push(tr);
while (!qb.empty()) {
bt *nw=qb.front();qb.pop();
if (nw) {cnt++;qb.push(nw->lc);qb.push(nw->rc);}
if (nw==nullptr) {
if (cnt==n) printf("YES %d\n",last);
else printf("NO %d\n",root);
return;
}
else last=nw->data;
}
}
int main() {
cin>>n;
for (int i=0;i<n;i++) { //最后换了流输入输出才搞好,真是无聊
string l,r;
cin>>l>>r;
if (l=="-")
if (r=="-") a=-1,b=-1;
else a=-1,b=stoi(r);
else
if (r=="-") a=stoi(l),b=-1;
else a=stoi(l),b=stoi(r);
vpi.push_back({a,b});
if (0<=a) lo[a]=true;
if (0<=b) lo[b]=true;
}
for (int i=0;i<n;i++)
if (!lo[i]) {root=i;break;}
bt* tree=buildTree(root);
levelTraversal(tree);
return 0;
}