PAT甲级——A1110 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
 1 #include <iostream>
 2 #include <vector>
 3 #include <queue>
 4 #include <string>
 5 using namespace std;
 6 struct Node
 7 {
 8     int l, r;
 9 }node;
10 int n;
11 int main()
12 {
13     cin >> n;
14     vector<Node>tree;
15     vector<bool>isRoot(n, true);
16     for (int i = 0; i < n; ++i)
17     {
18         string s1, s2;
19         cin >> s1 >> s2;
20         if (s1 == "-")
21             node.l = -1;
22         else
23         {
24             node.l = atoi(s1.c_str());
25             isRoot[node.l] = false;
26         }
27         if (s2 == "-")
28             node.r = -1;
29         else
30         {
31             node.r = atoi(s2.c_str());
32             isRoot[node.r] = false;
33         }
34         tree.push_back(node);
35     }
36     int root = -1;//
37     for (int i = 0; i < n && root==-1; ++i)
38         if (isRoot[i])
39             root = i;
40     queue<int>q, temp;
41     q.push(root);
42     while (!q.empty())//进行层序遍历
43     {
44         int p = q.front();
45         q.pop();
46         temp.push(p);//保存弹出的数据
47         if (tree[p].l != -1)
48             q.push(tree[p].l);
49         else
50             break;//出现空子节点,则打破了完全二叉树的规则
51         if (tree[p].r != -1)
52             q.push(tree[p].r);
53         else
54             break;//出现空子节点,则打破了完全二叉树的规则
55     }
56     if (temp.size() + q.size() == n)//满足完全二叉树的要求
57         cout << "YES " << q.back() << endl;//最后压入的就是最后一个节点
58     else
59         cout << "NO " << root << endl;
60     return 0;
61 }

猜你喜欢

转载自www.cnblogs.com/zzw1024/p/11449169.html