第十四周專案6 二叉排序樹中查詢的路徑

2021-07-25 05:53:45 字數 3545 閱讀 4320

/*   

* 檔名稱:專案6.cpp

* 作 者:梁凱

* 完成日期:2023年12月2日

* 版 本 號:v1.0

* 問題描述:設計乙個演算法,輸出在二叉排序中查詢時查詢某個關鍵字經過的路徑。

* 輸入描述:無

* 程式輸出:測試資料

*/

//標頭檔案    

#ifndef graph_h_included

#define graph_h_included

#define maxv 100 //最大頂點個數

#define inf 32767 //inf表示∞

typedef int infotype;

//以下定義鄰接矩陣型別

typedef struct

vertextype; //頂點型別

typedef struct //圖的定義

mgraph; //圖的鄰接矩陣型別

//以下定義鄰接表型別

typedef struct anode //弧的結點結構型別

arcnode;

typedef int vertex;

typedef struct vnode //鄰接表頭結點的型別

vnode;

typedef vnode adjlist[maxv]; //adjlist是鄰接表型別

typedef struct

algraph; //圖的鄰接表型別

//功能:由乙個反映圖中頂點鄰接關係的二維陣列,構造出用鄰接矩陣儲存的圖

//引數:arr - 陣列名,由於形式引數為二維陣列時必須給出每行的元素個數,在此將引數arr宣告為一維陣列名(指向int的指標)

// n - 矩陣的階數

// g - 要構造出來的鄰接矩陣資料結構

void arraytomat(int *arr, int n, mgraph &g); //用普通陣列構造圖的鄰接矩陣

void arraytolist(int *arr, int n, algraph *&); //用普通陣列構造圖的鄰接表

void mattolist(mgraph g,algraph *&g);//將鄰接矩陣g轉換成鄰接表g

void listtomat(algraph *g,mgraph &g);//將鄰接表g轉換成鄰接矩陣g

void dispmat(mgraph g);//輸出鄰接矩陣g

void dispadj(algraph *g);//輸出鄰接表g

#endif // graph_h_included

//原始檔   

#include #include #include "graph.h"

//功能:由乙個反映圖中頂點鄰接關係的二維陣列,構造出用鄰接矩陣儲存的圖

//引數:arr - 陣列名,由於形式引數為二維陣列時必須給出每行的元素個數,在此將引數arr宣告為一維陣列名(指向int的指標)

// n - 矩陣的階數

// g - 要構造出來的鄰接矩陣資料結構

void arraytomat(int *arr, int n, mgraph &g)

g->e=count;

}

void mattolist(mgraph g, algraph *&g)

//將鄰接矩陣g轉換成鄰接表g

g->n=g.n;

g->e=g.e;

}

void listtomat(algraph *g,mgraph &g)

//將鄰接表g轉換成鄰接矩陣g

} }

void dispmat(mgraph g)

//輸出鄰接矩陣g

printf("\n");

} }

//主函式  

#include #include #define maxsize 100

typedef int keytype; //定義關鍵字型別

typedef char infotype;

typedef struct node //記錄型別

bstnode;

int path[maxsize]; //全域性變數,用於存放路徑

void dispbst(bstnode *b); //函式說明

int insertbst(bstnode *&p,keytype k) //在以*p為根節點的bst中插入乙個關鍵字為k的節點

else if (k==p->key)

return 0;

else if (kkey)

return insertbst(p->lchild,k); //插入到*p的左子樹中

else

return insertbst(p->rchild,k); //插入到*p的右子樹中

} bstnode *creatbst(keytype a,int n)

//由陣列a中的關鍵字建立一棵二叉排序樹

else

}

//查詢並顯示經過的路徑

void searchresult(bstnode *bt, int k1)

void dispbst(bstnode *bt)

//以括號表示法輸出二叉排序樹bt

} }

int main()

,n=10;

printf("建立的bst樹:");

bt=creatbst(a,n);

dispbst(bt);

printf("\n");

printf(" 查詢%d關鍵字:",k1);

searchresult(bt,k1);

printf(" 查詢%d關鍵字:",k2);

searchresult(bt,k2);

return 0;

}

執行結果:

第十四周專案6 二叉排序樹中查詢的路徑

檔名稱 專案6.cpp 作 者 田藝 完成日期 2016年12月2日 版 本 號 v1.0 問題描述 設計乙個演算法,輸出在二叉排序中查詢時查詢某個關鍵字經過的路徑。輸入描述 無 程式輸出 測試資料 標頭檔案 ifndef graph h included define graph h includ...

第十四周 專案4 二叉排序樹

標頭檔案 ifndef graph h included define graph h included define maxv 100 最大頂點個數 define inf 32767 inf表示 typedef int infotype 以下定義鄰接矩陣型別 typedef struct vert...

第十四周專案1二叉排序樹

檔名稱 h1.cpp 完成日期 2015年12月4日 版本號 vc6.0 問題描述 二叉排序樹 輸入描述 無 程式輸出 二叉樹建立刪除結果 include include typedef int keytype typedef char infotype 10 typedef struct node...