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 (<=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
结题思路:
题意要求我们对构建的树,判断是否为完全二叉树(满二叉树属于完全二叉树)。
要求1:不需要考虑非完全二叉树可能会出现的森林的情况,题目要求输出该树的根节点,而森林有的是根节点的集合;
要求2:完全二叉树在最后第二层及以上是满二叉树,最后一层的叶子节点全部位于左侧;
要求3:完全二叉树与非完全二叉的不同点在于,非完全二叉树在遍历到最后一个节点之前就能找到空节点。
程序步骤:
第一步我们建立了双向指针的树;
第二步寻找跟节点;
第三步从根节点开始我们进行层次遍历, 由于节点的是从0-N编号的,我们将空节点的值置为-1,当抛出空节点时,检查总长度跟当前的输出长度。
具体程序(AC)如下:
#include <iostream>
#include <queue>
#include <vector>
#include <string>
#include <cstring>
using namespace std;
struct node{
int parent;
int left;
int right;
node():parent(-1),left(-1),right(-1){}
};
int findRoot(vector<node>& tree)
{
for(int i=0;i<tree.size();++i)
if(tree[i].parent==-1)
return i;
}
bool isCompleteTree(vector<node>& tree,int root,int& last)
{
queue<int> q;
q.push(root);
int len=tree.size();
int curLen=0;
int cur=-1;
while(q.front()!=-1)
{
cur=q.front();
q.push(tree[cur].left);
q.push(tree[cur].right);
last=cur;
++curLen;
q.pop();
}
if(len==curLen)
return true;
return false;
}
int main() {
// your code goes here
vector<node> tree;
int n;
cin>>n;
tree.resize(n);
string tmp;
int index;
for(int i=0;i<n;++i)
{
cin>>tmp;
if(tmp[0]!='-')
{
index=atoi(tmp.c_str());
tree[i].left=index;
tree[index].parent=i;
}
cin>>tmp;
if(tmp[0]!='-')
{
index=atoi(tmp.c_str());
tree[i].right=index;
tree[index].parent=i;
}
}//buildTree
int root=findRoot(tree);
int last=-1;
if(isCompleteTree(tree,root,last))
cout<<"YES "<<last<<endl;
else
cout<<"NO "<<root<<endl;
return 0;
}