二叉排序树的创建,查找,遍历

 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

输出:

创建的二叉排序树为:

猜你喜欢

转载自www.cnblogs.com/diandianer/p/10084635.html