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

该博客探讨如何判断一棵二叉树是否为完全二叉树。提供了两种方法:一种是通过给节点标记并检查最后一个节点的值;另一种是利用广度优先遍历,观察是否在遍历过程中遇到空洞时已遍历完整棵树。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


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


给你一颗二叉树,让你判断是否为完全二叉树...


方法一: 给每个节点标记一下,例如,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;
}







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值