PAT (Advanced Level)1110 Complete Binary Tree (25分)

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

坑點:特判n=1時的情況

#include<bits/stdc++.h>
using namespace std;
struct node{
	int data;
	int lchild,rchild;
};

const int maxn = 50;
node t[maxn];

int levelorder(int root){
	queue<int> q;
	q.push(root);
	int lastnode;
	int flag=1;
	while(!q.empty()){
		int temp = q.front();
		q.pop();
		if(flag == 0 && t[temp].lchild != -1){
			return root;
		}
		if(t[temp].lchild != -1){
			q.push(t[temp].lchild);
		}else{
			flag = 0;
		}
		if(flag == 0 && t[temp].rchild != -1){
			return root;
		}
		if(t[temp].rchild != -1){
			q.push(t[temp].rchild);
		}else{
			flag = 0;
		}
		if(q.empty()) lastnode = temp; 
	}
	return lastnode;
}

int main(){
	int n;
	scanf("%d",&n);
	if(n==1){
		printf("YES 0");
		return 0;
	}
	int exist[n];
	fill(exist,exist+n,0);
	string lchild,rchild;
	for(int i=0;i<n;i++){
		cin>>lchild>>rchild;
		t[i].data = i;
		if(lchild!="-"){
			exist[stoi(lchild)] = 1;
			t[i].lchild = stoi(lchild);
		}else{
			t[i].lchild = -1;
		}
		if(rchild!="-"){
			exist[stoi(rchild)] = 1;
			t[i].rchild = stoi(rchild);
		}else{
			t[i].rchild = -1;
		}
	}
	int root;
	for(int i=0;i<n;i++){
		if(exist[i] == 0){
			root = i;
		}
	}
	int flag = levelorder(root);
	if(flag == root){
		printf("NO %d",root);
	}else{
		printf("YES %d",flag);
	}
	return 0;
}
發佈了37 篇原創文章 · 獲贊 16 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章