1110. Complete Binary Tree [判断完全二叉树]

今天开启了PAT第一题,纪念一下~~~(^▽ ^)

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个结点,随后给出从0到N-1个结点的左结点和右结点,让你判断是否是一棵完全二叉树。

题目重点:

No1:stoi(&string)将数组转化为十进制的整数

No2:判断是否是的思路,将每一个结点存入数组中,并且利用完全二叉树的下标作为数组下标的值,对应存入,最后判断数组下标是否>N 大于则不是完全二叉树

No3:vector 时一定要用resize提前开辟数组大小

#include<iostream>
#include<vector>
#include<string>
using namespace std;
int N;
vector<int>tree;
struct node {
	int l, r;
	int parent = -1;
}node[10000];
int getroot() 
{
	cin >> N;
	tree.resize(N + 1);//No3
	string a, b;  //No1
	for (int i = 0; i < N; i++) {
		cin >> a >> b;
		if (a != "-") {
			node[i].l = stoi(a); //No1
			node[stoi(a)].parent = i;
		}
		else
			node[i].l = -1;
		if (b != "-") {
			node[i].r = stoi(b);
			node[stoi(b)].parent = i;
		}
		else
			node[i].r = -1;
	}
	for (int i = 0; i < N; i++)
		if (node[i].parent == -1) 
			return i;
}
bool flag = true;
void createandjudge(int rootindex, int id)
{
	if (id > N){  //No2
		flag = false;
		return;
	}
	tree[id] = rootindex;
	if (node[rootindex].l != -1) createandjudge(node[rootindex].l, id * 2);
	if (node[rootindex].r != -1) createandjudge(node[rootindex].r, id * 2+1);
}
int main()
{
	int root = getroot();
	createandjudge(root, 1);
	if (flag == true) cout << "YES" << " " << tree[N];
	else cout << "NO" << " " << root;
}
posted @ 2020-05-18 23:29  _Hsiung  阅读(91)  评论(0编辑  收藏  举报