題目鏈接:https://www.patest.cn/contests/pat-a-practise/1110
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
完全二叉樹判斷思路:層序遍歷,一個完全二叉樹中,當遍歷到某個結點沒有子結點時,那麼它後面的所有結點都應該沒有子結點。
#include <iostream>
#include <queue>
#include <cstring>
#include <string>
using namespace std;
struct BTree {
int lchild,rchild;
};
BTree T[25];
bool notRoot[25];
int thisone = -1; // 層序遍歷時當前訪問的節點序數
bool LevelOrder(int root)
{
queue<int> qt;
qt.push(root);
bool nochild = false;
while (!qt.empty()) {
thisone = qt.front();
qt.pop();
if(T[thisone].lchild!=-1){
if(nochild)
return false;
qt.push(T[thisone].lchild);
}
else
nochild = true;
if(T[thisone].rchild!=-1){
if(nochild)
return false;
qt.push(T[thisone].rchild);
}
else
nochild = true;
}
return true;
}
int GetRootIndex()
{
int i = 0;
while (notRoot[i]) {
++i;
}
return i;
}
int main()
{
memset(notRoot, 0, sizeof(notRoot));
int num;
cin >> num;
for(int i = 0; i < num; ++i)
{
char str[3];
int temp;
scanf("%s", str);
if(str[0] == '-') T[i].lchild = -1;
else {
sscanf(str, "%d", &temp);
T[i].lchild = temp;
notRoot[temp] = true;
}
scanf("%s", str);
if(str[0] == '-') T[i].rchild = -1;
else {
sscanf(str, "%d", &temp);
T[i].rchild = temp;
notRoot[temp] = true;
}
}
int rootIndex = GetRootIndex();
if(LevelOrder(rootIndex))
cout << "YES" << " " << thisone << endl;
else
cout << "NO" << " " << rootIndex << endl;
return 0;
}