题目大意:给出一棵二叉树的结构,判断是否是完全二叉树。
核心问题是如何判断一棵树是否是完全二叉树?要利用完全二叉树的层序遍历的性质:完全二叉树在进行层序遍历时,前N个节点都应该是非空节点。
那么进行层序遍历,每次正常的将当前节点左右孩子加入队列,如果某一次已经遍历完的节点个数<=N,但是当前节点为空,说明不是完全二叉树;否则,顺利遍历完N个非空节点,说明是完全二叉树。
AC代码:
#include <iostream>
#include <vector>
#include <cstdio>
#include <queue>
using namespace std;
struct Node
{
int left;
int right;
}allNodes[30];
bool levelOrder(int node, vector<int> &tree)
{
queue<int> q;
q.push(node);
int cnt = 0;
while(!q.empty())
{
int now = q.front();
q.pop();
tree[cnt++] = now;
if(now == -1 && cnt <= tree.size()) return false;
else if(cnt == tree.size()) return true;
q.push(allNodes[now].left);
q.push(allNodes[now].right);
}
}
int main()
{
int N;
cin >> N;
vector<bool> isNotRoot(N, 0);
for (int i = 0; i < N; ++i)
{
string left, right;
cin >> left >> right;
if(left == "-") allNodes[i].left = -1;
else
{
allNodes[i].left = stoi(left);
isNotRoot[stoi(left)] = true;
}
if(right == "-") allNodes[i].right = -1;
else
{
allNodes[i].right = stoi(right);
isNotRoot[stoi(right)] = true;
}
}
vector<int> tree(N);
int root = 0;
for (int i = 0; i < N; ++i)
if(!isNotRoot[i]) root = i;
if(levelOrder(root, tree)) printf("YES %d", tree[N-1]);
else printf("NO %d", root);
return 0;
}