家谱二叉树c语言程序
时间: 2024-05-21 15:08:42 浏览: 22
家谱二叉树是一种二叉树,用于存储家族成员之间的关系,具体来说,每个节点代表一个人,节点中保存着该人的信息和该人的父亲和母亲节点。下面是一个简单的家谱二叉树c语言程序的实现:
```
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
//定义节点结构体
typedef struct node{
char name[20];
char sex;
char spouse[20];
struct node *father;
struct node *mother;
}Node;
//初始化根节点
Node *init(){
Node *root=(Node*)malloc(sizeof(Node));
strcpy(root->name,"根节点");
root->father=NULL;
root->mother=NULL;
return root;
}
//添加子女节点
void add(Node *parent,char name[],char sex[],char spouse[]){
Node *child=(Node*)malloc(sizeof(Node));
strcpy(child->name,name);
strcpy(child->sex,sex);
strcpy(child->spouse,spouse);
child->father=parent;
child->mother=parent->spouse!=NULL?parent->spouse:NULL;
if(parent->sex=='男'){
parent->father!=NULL?add(parent->father,name,sex,spouse):NULL;
parent->father==NULL&&parent->mother!=NULL?add(parent->mother,name,sex,spouse):NULL;
}else{
parent->mother!=NULL?add(parent->mother,name,sex,spouse):NULL;
parent->mother==NULL&&parent->father!=NULL?add(parent->father,name,sex,spouse):NULL;
}
}
//按照层序遍历输出所有节点信息
void print(Node *root){
Node *queue[100];
int front=0,rear=0;
queue[rear++]=root;
while(front!=rear){
Node *temp=queue[front++];
printf("姓名:%s 性别:%s 配偶:%s 父亲:%s 母亲:%s\n",temp->name,temp->sex,temp->spouse,temp->father!=NULL?temp->father->name:"无",temp->mother!=NULL?temp->mother->name:"无");
if(temp->father!=NULL)queue[rear++]=temp->father;
if(temp->mother!=NULL)queue[rear++]=temp->mother;
}
}
int main(){
Node *root=init();
add(root,"张三","男","李四");
add(root,"李四","女","张三");
add(root,"王五","男",NULL);
add(root,"赵六","女","钱七");
print(root);
return 0;
}
```
上述代码实现了家谱二叉树的基本功能,包括初始化根节点、添加子女节点、按照层序遍历输出所有节点信息。在使用时,可以根据需要添加、删除或修改节点,以满足实际需求。