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
题目大意:完全二叉树的判断
解题思路:可以利用完全二叉树的层次遍历的序号连续这个特点,用DFS和BFS遍历
DFS:利用 i 节点的左右节点分别为2*i,2*i+1这一特点,若为完全二叉树,则最后一个节点序号为n(从1开始),换言之,若某树不是完全二叉树,则一定有节点的序号超过n,我们只对index小于等于n的节点计数,如果最后结果小于n,就一定为非完全二叉树。
#include <iostream>
#include <string>
using namespace std;
int tree[25][2], root = 0, n, cnt = 0, ans;
bool visit[25];
void dfs(int id, int index){
if(index > n || id == -1)
return;
++ cnt;
if(index == n)
ans = id;
dfs(tree[id][0], 2 * index);
dfs(tree[id][1], 2 * index + 1);
}
int main(){
scanf("%d", &n);
for(int i = 0; i < n; ++ i){
string a, b;
int tempa, tempb;
cin >> a >> b;
if(a != "-"){
tempa = stoi(a);
tree[i][0] = tempa;
visit[tempa] = true;
}
else
tree[i][0] = -1;
if(b != "-"){
tempb = stoi(b);
tree[i][1] = tempb;
visit[tempb] = true;
}
else
tree[i][1] = -1;
}
while(visit[root])
++ root;
dfs(root, 1);
if(cnt == n)
printf("YES %d", ans);
else
printf("NO %d", root);
}
BFS:计数法,当遇到第一个节点的左右孩子不全有值,则所有的节点均已遍历,即cnt等于n,若小于,则非完全二叉树。
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
int n, root = 0, cnt = 1, temp;
std::vector<int> tree[25];
int visit[25];
int main(){
cin>>n;
getchar();
for(int i = 0; i < n; i++){
tree[i].resize(2,-1);
string left, right;
cin>>left>>right;
if(left[0] != '-'){
int a = stoi(left);
tree[i][0] = a;
visit[a] = true;
}
if(right[0] != '-'){
int a = stoi(right);
tree[i][1] = a;
visit[a] = true;
}
}
while(visit[root] == true)
root++;
queue<int>q;
q.push(root);
while(!q.empty()){
temp = q.front();
q.pop();
if(tree[temp][0] != -1){
cnt ++;
q.push(tree[temp][0]);
}
else
break;
if(tree[temp][1] != -1){
cnt++;
q.push(tree[temp][1]);
}
else
break;
}
if(q.empty())
q.push(temp);
if(cnt < n)
printf("NO %d",root);
else
printf("YES %d",q.back());
}