双亲数组表示法——平时笔记

本文介绍了一种名为PATree的数据结构,并详细展示了如何通过C语言实现PATree中节点的父节点查找、所有祖先节点查找及子节点查找等功能。文章通过具体的函数实现,帮助读者理解PATree的工作原理。

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

#include <stdio.h>
#define MAX 100
#define EXIST           0
#define IS_ROOT        -1
#define PARAMETER_ERR  -2
#define NOT_EXIST      -3
#define ERROR          -4
typedef char DataType;
typedef struct
{
	DataType data;
	int parent;
}PATreeNode;
typedef struct
{
	PATreeNode nodes[MAX];
	int n;
}PATree;
int FindParent_PATree(PATree T,int i)
{
	int id_parent;
	DataType val_parent;
	id_parent=T.nodes[i].parent;
	if(IS_ROOT==id_parent)
	{
		printf("The node %d is root,so it has no parent.",i);
	}
	else
	{
		val_parent=T.nodes[id_parent].data;
		printf("The ID of parent of node %d is %d.\n",i,id_parent);
		printf("The value of parent of node %d is %c.\n",i,val_parent);
	}
	return 0;
}
int FindParent_ID_PATree(PATree T,int i)
{
	int id_parent;
	if(i<0||i>=T.n)
	{
		printf("The paramter i is error!");
		return PARAMETER_ERR;
	}
	id_parent=FindParent_PATree(T,i);
	return id_parent;
}
int GetNodeID_PATree(PATree T,DataType val)
{
	int i;
	for(i=0;i<=T.n-1;i++)
	{
		if(val==T.nodes[i].data)
			return i;
	}
	return NOT_EXIST;
}
void FindParent_val_PATree(PATree T,DataType val)
{
	int id;
	id=GetNodeID_PATree(T,val);
	if(NOT_EXIST==id)
	{
		printf("The tree does not include the node %c.\n",val);
		return;
	}
	FindParent_PATree(T,id);
}
void FindAllAncestor_PATree(PATree T,int i)
{
	int id_parent=i;
	while(IS_ROOT!=id_parent)
	{
		id_parent=FindParent_PATree(T,id_parent);
	}
}
void FindAllAncestor_ID_PATree(PATree T,int i)
{
	int id_parent;
	id_parent=FindParent_ID_PATree(T,i);
	if(PARAMETER_ERR==id_parent)
		return;
	FindAllAncestor_PATree(T,id_parent);
}
void FindAllAncestor_Val_PATree(PATree T,DataType val)
{
	int id;
	id=GetNodeID_PATree(T,val);
	if(NOT_EXIST==id)
	{
		printf("The tree does not include the node %c.\n",val);
		return;
	}
	FindAllAncestor_PATree(T,id);
}
int FindChildren_PATree(PATree T,int i)
{
	int k;
	int count_children=0;
	for(k=0;k<=T.n-1;i++)
	{
		if(T.nodes[k].parent==i)
		{
			count_children++;
			printf("This Node is NO.%d child of node %d:\n",count_children,i);
			printf("The ID of the child node is %d, ",k);
			printf("The value of the child node is %c.\n",T.nodes[k].data);
		}
	}
	return count_children;
}
int main()
{
	printf("ok!\n");
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值