第1个回答 2008-11-13
写好了,我考虑的问题比较细,所以代码有点长
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
/* The MAXSIZE number of node */
#define MAXSIZE 100
/* Save the content of node */
int Tree[MAXSIZE];
/* The number of node */
int number = 0;
void Initialize(int *);
void FindRelation (int *, int i);
void Display(int *);
void main()
{
/* The result of read from key buffer */
int iReadRlt = 0;
/* The suffix of node to search */
int search = 0;
/* Initialization */
memset(Tree, 0, MAXSIZE*sizeof(int));
/* Prompt user to input the number of node */
printf("请输入结点个数: ");
iReadRlt = scanf("%d", &number);
/* The input isn't a number or is illeagle */
while (0 >= iReadRlt || number < 0 || number > MAXSIZE)
{
/* Clear the key buffer */
while (10 != getchar())
{
continue;
}
printf("\n错误,请输入一个1-%d的数字: ", MAXSIZE);
iReadRlt = scanf("%d", &number);
}
/* Clear the key buffer */
while (10 != getchar())
{
continue;
}
/* Initialize the tree */
Initialize(Tree);
/* Prompt user to input the node */
printf("\n请输入你要查找的结点: ");
iReadRlt = scanf("%d", &search);
/* The input isn't a number */
while (0 >= iReadRlt)
{
/* Clear the key buffer */
while (10 != getchar())
{
continue;
}
printf("\n错误,请输入一个数字: ");
iReadRlt = scanf("%d", &search);
}
/* Clear the key buffer */
while (10 != getchar())
{
continue;
}
/* Display the node's parent and children */
FindRelation(Tree, search);
/* Display all the nodes of the tree */
printf("按前序遍历的顺序显示树的内容:\n\n");
Display(Tree+1);
printf("\n\n");
}
/* This function is to initialize the tree */
void Initialize(int * tree)
{
/* The counter of loop */
int count = 1;
/* The result of read form key buffer */
int iReadRlt = 0;
/* The first node don't save data */
tree[0] = -1;
for (; count <= number; count++)
{
/* Prompt user to input the content of node */
printf("\n请输入结点%d的内容: ",count);
iReadRlt = scanf("%d", &tree[count]);
/* The input isn't a number */
while (0 >= iReadRlt)
{
/* Clear the key buffer */
while (10 != getchar())
{
continue;
}
printf("\n错误,请输入一个数字: ");
iReadRlt = scanf("%d", &Tree[count]);
}
/* Clear the key buffer */
while (10 != getchar())
{
continue;
}
}
for (; count < MAXSIZE; count++)
{
tree[count] = -1;
}
}
/* This function is to get the parents and son nodes */
void FindRelation (int * tree, int i)
{
/* The node isn't exist */
if (i < 1 || i > number)
{
printf("\n该结点不存在!\n\n");
return;
}
/* The node is root */
if (1 == i)
{
printf("\n该结点是根结点,没有父结点.\n\n");
}
else
{
printf("\n该结点的父结点是: %d\n\n", tree[i/2]);
}
/* The node don't have child */
if (i+i > number)
{
printf("该结点没有子结点!\n\n");
}
else if (i+i+1 > number)
{
printf("该结点只有一个子结点: %d\n\n", tree[i+i]);
}
else
{
printf("该结点的子结点: %d, %d\n\n", tree[i+i], tree[i+i+1]);
}
}
void Display(int * root)
{
int suffix = 0;
/* The node is empty */
if (root > Tree+number)
{
return;
}
/* Display the root node */
printf("%d ", root[0]);
suffix = root - Tree;
/* Display the left subtree */
Display(Tree+suffix+suffix);
/* Display the right subtree */
Display(Tree+suffix+suffix+1);
}