二叉排序树与前序中序输出

1.二叉排序树的概念:
  二叉排序树是一种动态树表。
   二叉排序树的定义:二叉排序树或者是一棵空树,
   或者是一棵具有如下性质的二叉树:
     ⑴ 若它的左子树非空,则左子树上所有结点的值均小于根结点的值;
     ⑵ 若它的右子树非空,则右子树上所有结点的值均大于根结点的值;
     ⑶ 左、右子树本身又各是一棵二叉排序树。二叉排序树的性质: 按中序遍历二叉排序树,所得到的中序遍历序列是一个递增有序序列

2.二叉排序树的插入:
   在二叉排序树中插入新结点,要保证插入后的二叉树仍符合二叉排序树的定义。
   插入过程:若二叉排序树为空,则待插入结点*S作为根结点插入到空树中;
   当非空时,将待插结点关键字S->key和树根关键字t->key进行比较,
   若s->key = t->key,则无须插入,若s->key< t->key,则插入到根的左子树中,
   若s->key> t->key,则插入到根的右子树中。而子树中的插入过程和在树中的插入过程相同,
   如此进行下去,直到把结点*s作为一个新的树叶插入到二叉排序树中,或者直到发现树已有相同关键字的结点为止。

3. 二叉排序树生成:
   从空的二叉排序树开始,经过一系列的查找插入操作以后,生成了一棵二叉排序树。
   说明:
     ① 每次插入的新结点都是二叉排序树上新的叶子结点。
     ② 由不同顺序的关键字序列,会得到不同二叉排序树。
     ③ 对于一个任意的关键字序列构造一棵二叉排序树,其实质上对关键字进行排序。

 1 # include <stdio.h>
 2 # include <string.h>
 3 # include <malloc.h>
 4 char q1[100],q2[100];
 5 char num1[100],num2[100];
 6 static int k;
 7 struct node
 8 {
 9     int data;
10     struct node *l;
11     struct node *r;
12 };
13 struct node *Insert(struct node *T,int key)
14 {
15     struct node *p=T,*f=T;
16     while(p)
17     {
18         f=p;
19         if(key<p->data)
20             p=p->l;
21         else
22             p=p->r;
23     }
24     p=(struct node *)malloc(sizeof(struct node));
25     p->data=key;
26     p->l=NULL;
27     p->r=NULL;
28     if(T==NULL)
29     {
30         T=p;
31     }
32     else
33     {
34         if(key<f->data)
35             f->l=p;
36         else
37             f->r=p;
38     }
39     return T;
40 }
41 void Inorder(struct node *T,char *h)
42 {
43     if(T)
44     {
45         Inorder(T->l,h);
46         h[k++]=T->data;
47         Inorder(T->r,h);
48     }
49 }
50 void pre(struct node *T,char *h)
51 {
52     if(T)
53     {
54         h[k++]=T->data;
55         pre(T->l,h);
56         pre(T->r,h);
57     }
58 }
59 int main()
60 {
61     char a[100],b[100];
62     int i,j,n,m;
63     struct node *root,*root1;
64     while(scanf("%s",a)!=EOF)
65     {
66         getchar();
67         root=(struct node *)malloc(sizeof(struct node));
68         root=NULL;
69         n=strlen(a);
70         for(i=0;i<n;i++)
71         {
72             root=Insert(root,a[i]);
73         }
74         k=0;
75         pre(root,num1);
76         num1[k]='\0';
77         printf("%s\n",num1);
78         k=0;
79         Inorder(root,num2);
80         num2[k]='\0';
81         printf("%s\n",num2);
82     }
83     
84     return 0;
85 }
View Code

 

 

posted on 2013-08-06 16:10  随风浪子的博客  阅读(461)  评论(0编辑  收藏  举报

导航