1. 程式人生 > >二叉排序樹的建立,查詢,遍歷

二叉排序樹的建立,查詢,遍歷

 1 #include<stdio.h>
 2 #include <iostream>
 3 #include<algorithm>
 4 using namespace std;
 5 #define MAXSIZE 100
 6 typedef int KeyType;
 7 typedef char InfoType;
 8 #define ENDFLAG -1
 9 typedef struct
10 {
11     KeyType key;
12     InfoType otherinfo;
13 }ElemType;
14 typedef struct
BSTNode 15 { 16 ElemType data; 17 struct BSTNode *lchild,*rchild; 18 }BSTNode,*BSTree; 19 void InsertBST(BSTree &T,ElemType e)//在二叉排序樹T上插入值為e的記錄 20 { 21 BSTree S; 22 if(!T) 23 { 24 S=new BSTNode; 25 S->data=e; 26 S->lchild=S->rchild=NULL; 27 T=S;
28 } 29 else if(e.key<T->data.key) 30 InsertBST(T->lchild,e); 31 else if(e.key>T->data.key) 32 InsertBST(T->rchild,e); 33 } 34 void CreatBST(BSTree &T)//建立二叉排序樹 35 { 36 T=NULL; 37 ElemType e; 38 scanf("%d",&e.key); 39 while(e.key!=ENDFLAG)
40 { 41 InsertBST(T,e); 42 scanf("%d",&e.key); 43 } 44 } 45 BSTree SearchBST(BSTree T,int key)//在二叉排序樹T上查詢關鍵字為key的記錄 46 { 47 if(!T||key==T->data.key) 48 return T; 49 else if(key<T->data.key) 50 return SearchBST(T->lchild,key); 51 else 52 return SearchBST(T->rchild,key); 53 } 54 void InOrderTraverse(BSTree T)//中序遍歷二叉排序樹,得到有序序列 55 { 56 if(T) 57 { 58 InOrderTraverse(T->lchild); 59 printf("%d ",T->data.key); 60 InOrderTraverse(T->rchild); 61 } 62 } 63 int main() 64 { 65 int key; 66 BSTree T,p; 67 CreatBST(T); 68 InOrderTraverse(T); 69 printf("\n"); 70 scanf("%d",&key); 71 p=SearchBST(T,key); 72 if(p) 73 { 74 printf("查詢成功\n"); 75 if(p->lchild) 76 printf("%d的左子結點是%d ",key,p->lchild->data.key); 77 else 78 printf("%d沒有左子結點 ",key); 79 if(p->rchild) 80 printf("%d的右子結點是%d\n",key,p->rchild->data.key); 81 else 82 printf("%d沒有右子結點\n",key); 83 } 84 else 85 printf("查詢失敗\n"); 86 return 0; 87 }

 輸入:5 3 2 1 4 8 7 6 10 9 -1

            4

輸出:

建立的二叉排序樹為: