1110 Complete Binary Tree(判断是否是完全二叉树)

题目:https://pintia.cn/problem-sets/994805342720868352/problems/994805359372255232

算法思想:采用层次遍历,将所有结点(包括空结点)入队。当遇到空结点时,查看其后是否有非空结点。若有,则二叉树不是完全二叉树。

 1 #include<iostream>
 2 #include<vector>
 3 #include<queue>
 4 #include<map>
 5 using namespace std;
 6 
 7 struct Node {
 8     int lchild,rchild;
 9 };
10 
11 vector<Node> tree;
12 int lastNode;
13 int BFS(int root) {
14     if(root == -1) return 1;
15     queue<int> q;
16     q.push(root);
17     while(!q.empty()) {
18         int node = q.front();
19         if(node != -1) lastNode = node;
20         q.pop();
21         if(node != -1) {
22             q.push(tree[node].lchild);
23             q.push(tree[node].rchild);
24         } else {
25             while(!q.empty()) {
26                 int node = q.front();
27                 if(node != -1) return 0;
28                 q.pop();
29             }
30         }
31     }
32     return 1;
33 }
34 
35 int main() {
36     int n;
37     cin>>n;
38     tree.resize(n);
39     vector<int> hashtable(n);
40     for(int i = 0; i < n; ++i) {
41         string l,r;
42         cin>>l>>r;
43         tree[i].lchild = (l == "-"?-1: stoi(l));
44         tree[i].rchild = (r == "-"?-1: stoi(r));
45         if(tree[i].lchild != -1) hashtable[tree[i].lchild] = 1;
46         if(tree[i].rchild != -1) hashtable[tree[i].rchild] = 1;
47     }
48     int root;
49     for(int i = 0; i < n; ++i) if(hashtable[i] == 0) root = i;
50     if(BFS(root)) printf("YES %d",lastNode);
51     else printf("NO %d",root);
52     return 0;
53 }

猜你喜欢

转载自www.cnblogs.com/keep23456/p/12539571.html