利用顺序存储(数组)存储一棵完全二叉树,输出第i个数据元素的双亲和孩子

核心代码

if(temp==-1)
		printf("无结点\n");
	else if(temp==1)
		printf("无双亲\n");
	else
		printf("编号为%d为双亲\n",temp/2);
		
	if(2*temp>l)
			printf("无左孩子\n");
		else if(2*temp<=l)
			printf("左孩子为:%d\n",a[2*temp]);

	if((2*temp+1)>l)
			printf("无右孩子\n");
		else if((2*temp+1)<=l)
			printf("右孩子为:%d\n",a[2*temp+1]);
		else
			printf("wrong");

根据完全二叉树的定义
所有代码

#include<stdio.h>
#define MAX 10
int main()
{
	int a[MAX]={-1};
	int i=0;
	int temp;		//节点编号
	int l=0;
	do
	{
		i++;
		printf("请输入第%d个结点的值,若无为-1:",i);
		scanf("%d",&a[i]);
	}
	while(a[i]!=-1);		//输入二叉树
	for(i=1;a[i]!=-1;i++)
		{printf("第%d个节点值为:%d\n",i,a[i]);	l=i;}//输出二叉树,并统计个数
	printf("length:%d\n",l);	//输出二叉树节点个数
	printf("请输入要查找节点编号:");
	scanf("%d",&temp);
	if(temp==-1)
		printf("无结点\n");
	else if(temp==1)
		printf("无双亲\n");
	else
		printf("编号为%d为双亲\n",temp/2);
		
	if(2*temp>l)
			printf("无左孩子\n");
		else if(2*temp<=l)
			printf("左孩子为:%d\n",a[2*temp]);

	if((2*temp+1)>l)
			printf("无右孩子\n");
		else if((2*temp+1)<=l)
			printf("右孩子为:%d\n",a[2*temp+1]);
		else
			printf("wrong");
}

看完点赞!!!

猜你喜欢

转载自blog.csdn.net/The_Handsome_Sir/article/details/106220335
今日推荐