資料結構樹的雙親表示法
#include<iostream> #include<malloc.h> #include<stdlib.h> using namespace std;
#define max 100 typedef char TElemType; typedef struct { TElemType data; int parent; }PTNode;
typedef struct { PTNode node[max]; int n; }PTree;
void InitTree(PTree &tree) { char ch; int j; cout << "請輸入樹的節點個數" << endl; cin >> tree.n; cout << "請輸入結點的值和其雙親" << endl; for (int i = 0; i < tree.n; i++) { fflush(stdin); cin >> ch >> j; tree.node[i].data = ch; tree.node[i].parent = j; } tree.node[0].parent = -1; } void FindParent(PTree tree) { int i;; cout << "請輸入你要查詢的結點" << endl; cin >> i; cout << i << "的雙親為:" << tree.node[i].parent << endl; }
void FindChild(PTree tree) { int i; char ch; //cout << "請輸入你想要查詢孩子的雙親的序號" << endl; cout << "請輸入你想查詢孩子雙親的值" << endl;
cin >> ch; for (i = 0; i < tree.n; i++) { if (ch == tree.node[tree.node[i].parent].data) { cout << "該孩子的值為:"; cout << tree.node[i].data << endl; } } return;
}
int main() { PTree tree; InitTree(tree); //for (int i = 0; i < 10; i++) //FindParent(tree); for(int i=0;i<3;i++) FindChild(tree); return 0; }