編成實現功能: 創建一棵二元排序樹, 創建完成後輸入要查找的數據並進行對二元排序樹搜尋, 並將搜尋次數與結果顯示出來.
技術要點 :
二元排序樹是一棵具有如下特徵的非空二元樹 :
範例代碼 :
- #include
- #include
- struct bnode{
- struct bnode *lchild;
- char data;
- struct bnode *rchild;
- };
- typedef bnode *bitree;
- int searchBTree(bitree root, int key) {
- int n=0;
- if(root == NULL)
- return -1;
- bitree tmp = root;
- while(tmp != NULL) {
- n++;
- if(tmp->data > key) {
- tmp = tmp->lchild;
- } else if(tmp->data == key) {
- return n;
- } else {
- tmp = tmp->rchild;
- }
- }
- return -1;
- }
- void addNode(bitree *root, int val) {
- if(*root == NULL) {
- *root = (bitree) malloc(sizeof(bnode));
- (*root)->data = val;
- (*root)->lchild = NULL;
- (*root)->rchild = NULL;
- } else {
- bitree newtr = (bitree) malloc(sizeof(bnode));
- newtr->data = val;
- newtr->lchild = NULL;
- newtr->rchild = NULL;
- bitree tmp = *root;
- while(tmp != NULL) {
- if(tmp->data > val) { // 往左子樹
- if(tmp->lchild != NULL) {
- tmp = tmp->lchild;
- } else {
- tmp->lchild = newtr;
- break;
- }
- } else { // 往右子樹
- if(tmp->rchild != NULL) {
- tmp = tmp->rchild;
- } else {
- tmp->rchild = newtr;
- break;
- }
- }
- }
- }
- }
- void SC_113() {
- bitree root = NULL;
- int val = 0;
- while(val>=0) {
- printf("Please give val (-1 to leave): ");
- scanf("%d", &val);
- if(val>=0)
- addNode(&root, val);
- }
- printf("Please give search key: ");
- scanf("%d", &val);
- int n = searchBTree(root, val);
- if(n>0) {
- printf("Found in %d times!\n", n);
- } else {
- printf("Not found!");
- }
- free(root);
- }
補充說明 :
* [ 資料結構 小學堂 ] 樹狀結構導論 : 二元運算樹進階研究 - 二元排序樹
沒有留言:
張貼留言