#include<iostream>
#include<malloc.h>
using namespace std;
typedef char TElemType;
#define max 100
typedef struct Child
{
int data;
struct Child* next;
}*Tchild,Child;
typedef struct
{
int parent;
TElemType data;
Tchild firstchild;
}Jiedian;
typedef struct
{
Jiedian node[max];
int n, r;
}PTree;
void InitTree(PTree &tree)
{
tree.n = 0;
tree.r = 0;
}
void CreateTree(PTree &tree)
{
int count, i, j, k;
int child;
Tchild childhead = NULL, childptr = NULL, childtemp = NULL;
cout << "请输入树节点的总数" << endl;
cin >> count;
tree.n = count;
if (0 == count)
{
tree.n = 0;
return;
}
else
{
for (i = 0; i < count; i++)
{
cout << "请输入第" << i << "节点的值" << endl;
cin >> tree.node[i].data;
cout << "请输入它的双亲的序号" << endl;
cin >> tree.node[i].parent;
cout << "请输入它的孩子的数目" << endl;
cin >> j;
if (0 == j)
{
tree.node[i].firstchild = NULL;
continue;
}
else
{
childhead = (Tchild)malloc(sizeof(Child));
cout << "请输入第个孩子的序号的值" << endl;
cin >> child;
childhead->data = child;
childhead->next = NULL;
childptr = childhead;
if (j - 1 == 0)
{
tree.node[i].firstchild = childhead;
continue;
}
else
{
for (k = 0; k < j - 1; k++)
{
cout << "请输入第" << k + 2 << "个孩子的序号" << endl;
cin >> child;
childtemp = (Tchild)malloc(sizeof(Child));
childtemp->data = child;
childtemp->next = NULL;
childptr->next = childtemp;
childptr = childtemp;
}
tree.node[i].firstchild = childhead;
}
}
}
}
}
void FindChild(PTree tree)
{
TElemType ch;
Tchild ptr = NULL;
cout << "请输入你想要查找树的值" << endl;
cin >> ch;
for (int i = 0; i < tree.n; i++)
{
if (ch == tree.node[i].data)//找双亲
{
cout << ch << "的双亲的序号为:" << tree.node[i].parent << endl;
cout << "它的双亲的值为:" << tree.node[tree.node[i].parent].data << endl;
ptr = tree.node[i].firstchild;
if (NULL == ptr)
break;
else
{
int i = 1;
while (ptr!= NULL)
{
cout << "它的第" << i << "个孩子的值为" << tree.node[ptr->data].data << endl;
i++;
ptr = ptr->next;
}
}
}
}
}
int main()
{
PTree tree;
InitTree(tree);
CreateTree(tree);
FindChild(tree);
return 0;
}