假设我们用一棵二叉树存储你的家族族谱:对于任意一个结点来说,左支代表长子或长女,右支代表右第一兄弟或姐妹。结点存储的是每个人的姓名。
要求:输入某人的姓名,输出此人的所有兄弟姐妹。
参考代码
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#define NUM_NODE 50
typedef struct BiTree
{
int data;
struct BiTree *lchild;
struct BiTree *rchild;
} BiTree;
BiTree *CreateTree(int n)
{
BiTree *t;
if (n <= 0 || n > NUM_NODE)
return NULL;
if (!(t = (BiTree *)malloc(sizeof(BiTree))))
return NULL;
t->data = n;
printf("%d ", t->data);
t->lchild = CreateTree(2 * n);
t->rchild = CreateTree(2 * n + 1);
return t;
}
void rTree(BiTree *t)
{
printf("%d ", t->data);
if (t->rchild)
rTree(t->rchild);
}
BiTree *PreSeek(BiTree *T, int data)
{ BiTree *P = NULL;
if (T->data == data)
return T;
if (T->lchild)
P = PreSeek(T->lchild, data);
if (P==NULL && T->rchild)
P = PreSeek(T->rchild, data);
return P;
}
int main()
{
BiTree *root;
printf("创建树\n");
root = CreateTree(1);
int a;
BiTree *p;
printf("输入查找值: ");
scanf("%d", &a);
p = PreSeek(root, a);
if (p!=NULL)
rTree(p);
else
printf("没有找到\n");
return 0;
}
如有帮助,望采纳!谢谢!