c语言编程之二叉排序树
二叉排序树,又称为二叉查找树。它是一颗空树,或者是具有下面的性质的二叉树:
1、若它的左子树不空,则左子树上所有节点的值均小于它的根结构的值;
2、若它的右子树不空,则右子树上所有节点的值均大于它的根结构的值;
二叉排序树的建立主要由以下几个步骤组成:
1、查找
2、添加(插入)
完成了上面两个步骤一个二叉排序树就算是建立好了。
1 1 #include<stdio.h> 2 2 #include<stdlib.h> 3 3 4 4 typedef int element; 5 5 typedef struct Node{ 6 6 struct Node *lchild,*rchild; 7 7 element data; 8 8 }*pNode; 9 9 10 10 //search a data from a sort tree 11 11 element Sear_tree(pNode T,element num,pNode f,pNode *P) 12 12 { 13 13 if(!T) 14 14 { 15 15 *P=f; 16 16 printf("Tree is empty\n"); 17 17 return 0; 18 18 } 19 19 else if(num==(T->data)) 20 20 { 21 21 *P=T; 22 22 printf("find the data%d\n",(*P)->data); 23 23 return 1; 24 24 } 25 25 else if(num<(T->data)) 26 26 { 27 27 return Sear_tree(T->lchild,num,T,P); 28 28 } 29 29 else if(num>(T->data)) 30 30 { 31 31 return Sear_tree(T->rchild,num,T,P); 32 32 } 33 33 } 34 34 35 35 //delete a data from a sort tree 36 36 element Dele_tree() 37 37 { 38 38 39 39 } 40 40 41 41 //add a data from a sort tree 42 42 element Add_tree(pNode *T,element num) 43 43 { 44 46 //S=(pNode)malloc(sizeof(struct Node)); 45 47 if(!Sear_tree(*T,num,NULL,&P)) 46 48 { 47 49 S=(pNode)malloc(sizeof(struct Node)); 48 50 S->lchild=S->rchild=NULL; 49 53 { 50 54 *T=S; 51 55 (*T)->data=num; 52 56 printf("root data:%d\n",(*T)->data); 53 57 } 54 58 else if(num<(P->data)) 55 59 { 56 60 P->lchild=S; 57 61 (P->lchild)->data=num; 58 63 } 59 64 else 60 65 { 61 66 P->rchild=S; 62 67 (P->rchild)->data=num; 63 69 } 64 70 return 1; 65 71 } 66 72 else 67 73 return 0; 68 74 } 69 75 70 76 //init a sort tree 71 77 element Init_tree(pNode *T) 72 78 { 73 79 *T=NULL; 74 80 } 75 81 76 82 //build a sort tree 77 83 element Build_tree(pNode *T) 78 84 { 79 85 element data[]={62,88,58,47,35,73,51,99,37,93}; 80 86 element i=0; 81 87 for(;i<10;i++) 82 88 { 83 89 Add_tree(&T,data[i]); 84 90 } 85 91 } 86 92 87 93 element main() 88 94 { 89 95 pNode P=NULL; 90 96 pNode T=NULL; 91 97 Build_tree(&P); 92 98 Sear_tree(&P,93,NULL,&T); 93 99 }