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

#include<iostream>
#include<string>
#include<algorithm>
#include<queue>
#include<vector>
using namespace std;
int n;
int pnt[22];
struct TNode {
	int id;
	int left, right;
}tnode[22];
vector<int> v;
queue<int> qu;
int main() {
	cin >> n;
	for (int i = 0; i < 22; i++) {
		pnt[i] = -1;
	}
	for (int i = 0; i < n; i++) {
		string tmp1, tmp2;
		cin >> tmp1 >> tmp2;
		if (tmp1 != "-" && tmp2 != "-") {
			int tmp3 = stoi(tmp1), tmp4 = stoi(tmp2);
			tnode[i].left = tmp3;
			pnt[tmp3] = i; 
			tnode[i].right = tmp4;
			pnt[tmp4] = i;
		}
		else if (tmp1 != "-" && tmp2 == "-") {
			int tmp3 = stoi(tmp1);
			tnode[i].left = tmp3;
			pnt[tmp3] = i;
			tnode[i].right = -1;
		}
		else if (tmp1 == "-" && tmp2 != "-") {
			int tmp4 = stoi(tmp2);
			tnode[i].left = -1;
			tnode[i].right = tmp4;
			pnt[tmp4] = i;
		}
		else {
			tnode[i].left = -2;
			tnode[i].right = -2;
		}
	}
	int root, lastnode;
	for (int i = 0; i < n; i++) {
		if (pnt[i] == -1) {
			root = i;
			break;
		}
	}
	lastnode = root;
	qu.push(root);
	bool flag = 1;
	while (!qu.empty()) {
		int ft = qu.front();
		v.push_back(ft);
		qu.pop();
		if (ft != -1) {
			if (tnode[ft].left != -2) {
				qu.push(tnode[ft].left);
			}
			if (tnode[ft].right != -2) {
				qu.push(tnode[ft].right);
			}
		}
		if (qu.size() == 1) {
			lastnode = qu.front();
			if (lastnode == -1) lastnode = ft;
		}
	}
	for (int i = 0; i < n; i++) {
		if (v[i] < 0) {
			flag = 0;
			break;
		}
	}
	if (flag == 1) printf("YES %d", lastnode);
	else printf("NO %d", root);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41937767/article/details/87861169