题目来源:PAT (Advanced Level) Practice
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
words:
hence 因此 indices 指数 complete 完整的,完成的
题意:
给定二叉树的n个结点和其左右孩子的信息,判断这个二叉树是否为完全二叉树;
思路:
1. 通过这n个结点的左右孩子信息建立二叉树,用数组存储二叉树;
2. 层序遍历二叉树,遍历时给每个结点编号(从1到n),若每个结点的编号符合“根节点为r时左右孩子结点为2r和2r+1”这个规则则是完全二叉树,否则若有一个结点不符合则不是完全二叉树;
//PAT ad 1110 Complete Binary Tree
#include <iostream>
using namespace std;
#include <queue>
#define N 25
struct bt //二叉树
{
int left;
int right;
int nums;
int nums2;
}tree[N];
int abc(string s) //判断输入的左右子树是否为-1
{
if(s.front()=='-') return -1;
int sum=0;
for(int i=0;i<s.size();i++)
sum=sum*10+s[i]-'0';
return sum;
}
int lastNode;
bool BFS(int root) //对二叉树进行层序遍历
{
queue<int> qe;
qe.push(root); //根入队
int nums=1;
tree[root].nums=nums;
int x;
while(!qe.empty())
{
x=qe.front(); qe.pop();
if(tree[x].nums!=nums) return false; //不是完全二叉树
nums++;
if(tree[x].left!=-1) //左子树
{
qe.push(tree[x].left);
tree[tree[x].left].nums=tree[x].nums*2;
}
if(tree[x].right!=-1) //右子树
{
qe.push(tree[x].right);
tree[tree[x].right].nums=tree[x].nums*2+1;
}
}
lastNode=x; //最后一个结点
return true;
}
int main()
{
int n,i;
cin>>n;cin.ignore();
string left,right;
int root=(n-1)*n/2;
for(i=0;i<n;i++) //输入
{
cin>>left>>right;
tree[i].left=abc(left);
tree[i].right=abc(right);
if(tree[i].left!=-1) root-=tree[i].left;
if(tree[i].right!=-1) root-=tree[i].right;
}
if(BFS(root)) //输出
cout<<"YES "<<lastNode<<endl;
else
cout<<"NO "<<root<<endl;
return 0;
}