PAT 甲级 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 (≤) which is the total number of nodes in the tree -- and hence the nodes are numbered from 0 to N1. 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)n 行左右孩子结点,根结点为行中没有出现的结点;

判断是否为完全二叉树,则输出 (YES)末尾结点则输出(NO)根结点

AC判断完全二叉树】:1、[ 找出根结点 ]    2、[ DFS遍历 ]   3、[ 分类输出 ]

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 
 4 struct node{
 5     string left, right;
 6 } Node[21];
 7 
 8 int root= 0, maxn = -1, last;
 9 
10 void DFS(int root, int index)
11 {
12     if(index > maxn)
13     {
14         maxn = index;
15         last = root;
16     }
17     if(Node[root].left != "-") DFS(stoi(Node[root].left), index * 2);
18     if(Node[root].right != "-") DFS(stoi(Node[root].right), index * 2 + 1);
19 }
20 
21 int main()
22 {
23     int n; cin >> n;
24     vector<int> find_root(n, 0);
25     for(int i = 0; i < n; i++)
26     {
27         cin >> Node[i].left >> Node[i].right;
28         if(Node[i].left != "-") find_root[stoi(Node[i].left)] = 1;
29         if(Node[i].right != "-") find_root[stoi(Node[i].right)] = 1;
30     }
31     
32     while(root < n && find_root[root]) root++;
33     DFS(root, 1);
34     
35     if(n == maxn) cout << "YES " << last;
36     else cout << "NO " << root;
37     return 0;
38 }
View Code

Tips:vector<int> v(n, 0);  // 初始化

原文地址:https://www.cnblogs.com/kamisamalz/p/13605135.html