樹的雙親表示法
阿新 • • 發佈:2019-01-02
由於樹中的每個結點都有唯一的一個雙親結點,所以可用一組連續的儲存空間(一維陣列)儲存樹中的各個結點,陣列中的一個元素表示樹中的一個結點,每個結點含兩個域,資料域存放結點本身資訊,雙親域指示本結點的雙親結點在陣列中位置。
C語言程式碼實現:
#include<stdio.h>
#include<stdlib.h>
#define MAX_SIZE 20
typedef char ElemType;
typedef struct Snode //結點結構
{
ElemType data;
int parent;
}PNode;
typedef struct //樹結構
{
PNode tnode[MAX_SIZE];
int n; //結點個數
}Ptree;
void InitPNode(Ptree &tree)
{
int i,j;
char ch;
printf("請輸入結點個數:\n");
scanf("%d",&(tree.n));
printf("請輸入結點的序及值其雙親序號:\n");
for(i=0; i<tree.n; i++)
{
fflush(stdin);
scanf("%c,%d" ,&ch,&j);
tree.tnode[i].data = ch;
tree.tnode[i].parent = j;
}
tree.tnode[0].parent = -1;
}
void FindParent(Ptree &tree)
{
int i;
printf("請輸入要查詢的結點的序號\n");
scanf("%d",&i);
printf(" %c 的父親結點序號為 %d\n",tree.tnode[i].data,tree.tnode[i].parent);
}
int main()
{
Ptree tree;
InitPNode(tree);
while (1) //測試
FindParent(tree);
return 0;
}
測試結果: