今天來寫一下二叉查找樹的構造算法node
二叉查找樹:二叉查找樹的的特色是全部節點的值要大於其左節點的值,小於其右節點的值。。。算法
所以咱們在構造二叉查找樹的查找算法的時候老是用要查找的數來和節點的值作一個比較,若是節點的值大於要查找的數,那麼繼續查找其左節點,反之則繼續查找器右節點,一直到查找到你要的數。函數
本算法包括計算樹的高度,樹的葉子節點的數目,樹的全部節點的數目,以及樹的輸出。spa
1.頭文件code
1 #include <stdio.h> 2 #include <stdlib.h>
2.結構blog
1 typedef struct node 2 { 3 int data; 4 struct node *lchild, *rchild; 5 }btnode,*BTnode;
3.構造樹遞歸
BTnode Create() { int a; BTnode root; scanf("%d", &a);
//若是你輸入的數爲0,那麼就中止構建你所構建的分支 if (a == 0) return NULL; else { root = (BTnode)malloc(sizeof(btnode)); //分配內存地址 root->data = a; //賦值 root->lchild = Create(); //利用遞歸算法構造左分支和右分支 root->rchild = Create(); } return root; //最後返回這個二叉樹 }
4.計算樹的高度內存
1 int btdepth(BTnode bt) 2 { 3 int ldepth, rdepth; 4 if (bt == NULL) //若是樹爲空,則返回0 5 return 0; 6 else 7 { 8 ldepth = btdepth(bt->lchild); //分別利用遞歸求左分支的高度和右分支的高度,最後最高的那個分支加上根節點則是樹的高度 9 rdepth = btdepth(bt->rchild); 10 return (ldepth > rdepth ? ldepth + 1 : rdepth + 1); 11 } 12 }
5.計算樹的節點數博客
1 int ncount(BTnode bt) 2 { 3 if (bt == NULL) 4 return 0; 5 else 6 return (ncount(bt->lchild) + ncount(bt->rchild) + 1); //不斷的用遞歸求節點數,最後求的左分支的節點數加上右分支的節點數再加上根節點則是樹的全部的節點 7 }
6.計算樹的葉子節點數io
1 int lcount(BTnode bt) 2 { 3 if (bt == NULL) 4 return 0; 5 else if (bt->lchild == NULL&&bt->rchild == NULL) //若是節點的子節點爲空那麼就返回1,即表示只有一個節點,也就是一個葉子節點 6 return 1; 7 else 8 return (lcount(bt->lchild) + lcount(bt->rchild)); //利用遞歸求得知足子節點爲空的節點數 9 }
7.查找算法
1 void search(BTnode bt,int key) 2 { 3 while (bt != NULL) 4 { 5 if (bt->data == key) 查找成功,則退出循環 6 { 7 printf("查找成功!!\n"); 8 break; 9 } 10 else if (bt->data > key) //要查找的數小於節點值,則繼續查找左節點 11 bt = bt->lchild; 12 else //反之查找右節點 13 bt = bt->rchild; 14 } 15 if (bt == NULL) 16 printf("沒有找到!\n"); 17 }
8.輸出算法
1 void print(BTnode bt) //利用中序遍歷輸出數的節點值 2 { 3 if (bt != NULL) 4 { 5 printf("%d", bt->data); 6 print(bt->lchild); 7 print(bt->rchild); 8 } 9 }
9.主函數
1 void main() 2 { 3 int key; 4 BTnode root; 5 root = Create(); 6 printf("輸出二叉樹爲:\n"); 7 print(root); 8 printf("\n"); 9 printf("樹的高度爲:%d\n", btdepth(root)); 10 printf("樹的節點數爲:%d\n", ncount(root)); 11 printf("樹的葉子節點數爲:%d\n", lcount(root)); 12 printf("請輸入你要查找的數:"); 13 scanf("%d", &key); 14 search(root, key); 15 }
更多博客請訪問:http://www.livekeys.club/