標籤:style blog http color 資料 width
二叉排序數或者是一棵空樹,或者是一棵具有以下性質的二叉樹:
(1)若它有左子樹,則左子樹上所有結點的資料均小於根結點的資料。
(2)若它有右子樹,則右子樹上所有結點的資料均大於根結點的資料。
(3)左、右子樹本身又各是一棵二叉排序樹。
這樣,在尋找的時候,從根節點開始,若尋找的元素小於根節點則尋找其左子樹,否則尋找右子樹。
例如資料:
代碼如下:
1 #include <stdio.h> 2 #define ARRAYLEN 10 3 int source[] = {10,25,4,63,5,8,74,6,24,92}; 4 typedef struct bst 5 { 6 int data; 7 struct bst *left; 8 struct bst *right; 9 }BSTree;10 11 //向二叉排序樹中插入節點12 void InsertBST(BSTree *t,int key){13 BSTree *p,*parent,*head;14 15 if(!(p=(BSTree *)malloc(sizeof(BSTree *)))){16 printf("Error:malloc error");17 exit(0);18 }19 20 p->data = key;21 p->left = p->right = NULL;22 23 head = t;24 while(head){25 parent = head;26 if(key < head->data)27 head = head->left;28 else29 head = head->right;30 }31 32 if(key < parent->data)33 parent->left = p;34 else35 parent->right = p;36 }37 38 //建立二叉排序樹39 void CreateBST(BSTree *t,int data[],int n){40 int i;41 42 t->data = data[0];43 t->left = t->right = NULL;44 45 for(i = 1; i < n ; i++)46 InsertBST(t,data[i]);47 }48 49 //中序遍曆排序二叉樹50 void BST_LDR(BSTree *t){51 if(t){52 BST_LDR(t->left);53 printf("%d ",t->data);54 BST_LDR(t->right);55 }56 }57 58 //根據關鍵字尋找元素59 BSTree *FindKey(BSTree *t,int key){60 if(!t || key==t->data)61 return t;62 if(key<t->data)63 return FindKey(t->left,key);64 else65 return FindKey(t->right,key);66 }67 68 //主函數69 int main(){70 int i;71 BSTree p;72 int key; //尋找的關鍵字73 BSTree *p_find; 74 75 printf("排序前:\n");76 for(i = 0 ; i < ARRAYLEN ; i++)77 printf("%d ",source[i]);78 79 CreateBST(&p,source,ARRAYLEN); 80 printf("\n中序遍曆:\n");81 BST_LDR(&p);82 83 printf("請輸入要尋找的關鍵字:");84 scanf("%d",&key);85 p_find = FindKey(&p,key);86 87 if(p_find)88 printf("要找到的元素地址為:%x\n",p_find);89 }