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 8Sample Input 2:
8 - - 4 5 0 6 - - 2 3 - 7 - - - -Sample Output 2:
NO 1
给你一颗二叉树,让你判断是否为完全二叉树...
方法一: 给每个节点标记一下,例如,root=1,lson=2,rson=3....
最后判断最后一个节点的值是否等于N
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<queue>
using namespace std;
const int N = 22;
char s1[5],s2[5];
int pre[N],have[N];
queue<int>qu;
struct node
{
int l,r,num;
}a[N];
int main()
{
int i,j,n,l,root,flag=1,f,r;
scanf("%d",&n);
memset(pre,-1,sizeof(pre));
for(i=0;i<n;i++) {
scanf("%s%s",s1,s2);
l=r=-1;
if(s1[0]!='-') {
sscanf(s1,"%d",&l);
pre[l]=i;
}
if(s2[0]!='-') {
sscanf(s2,"%d",&r);
pre[r]=i;
}
a[i].l=l,a[i].r=r;
}
root=0;
while(pre[root]!=-1) root=pre[root];
a[root].num=1;
qu.push(root);
while(!qu.empty()) {
f=qu.front();
qu.pop();
l=a[f].l,r=a[f].r;
a[l].num=a[f].num<<1;
a[r].num=a[f].num<<1|1;
if(l!=-1) qu.push(l);
if(r!=-1) qu.push(r);
}
if(a[f].num==n) printf("YES %d\n",f);
else printf("NO %d\n",root);
return 0;
}
方法二是,遍历的时候把左右子树都扔进去,直到遍历到NULL时退出来,之后再判断一个队列里面有没有还有没遍历到的点
任意的一个二叉树,都可以补成一个满二叉树。这样中间就会有很多空洞。在广度优先遍历的时候,如果是满二叉树,或者完全二叉树,这些空洞是在广度优先的遍历的末尾,所以,但我们遍历到空洞的时候,整个二叉树就已经遍历完成了。而如果,是非完全二叉树,
我们遍历到空洞的时候,就会发现,空洞后面还有没有遍历到的值。这样,只要根据是否遍历到空洞,整个树的遍历是否结束来判断是否是完全的二叉树。
bool is_complete(tree *root){
queue q;
tree *ptr;
// 进行广度优先遍历(层次遍历),并把NULL节点也放入队列
q.push(root);
while ((ptr = q.pop()) != NULL)
{
q.push(ptr->left);
q.push(ptr->right);
}
// 判断是否还有未被访问到的节点
while (!q.is_empty())
{
ptr = q.pop();
// 有未访问到的的非NULL节点,则树存在空洞,为非完全二叉树
if (NULL != ptr)
{
return false;
}
}
return true;
}
该博客探讨如何判断一棵二叉树是否为完全二叉树。提供了两种方法:一种是通过给节点标记并检查最后一个节点的值;另一种是利用广度优先遍历,观察是否在遍历过程中遇到空洞时已遍历完整棵树。
1864

被折叠的 条评论
为什么被折叠?



