码迷,mamicode.com
首页 > 编程语言 > 详细

二叉排序树

时间:2017-03-11 21:38:13      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:int   中序   order   ret   color   span   log   clu   pre   

输入一系列整数,建立二叉排序树,并进行先、中、后序遍历

代码:

 1 #include<stdio.h>
 2 #include<string.h>
 3 struct Node{
 4     Node *lchild,*rchild;
 5     int c;
 6 }Tree[110];
 7 int loc;
 8 Node *create(){
 9     Tree[loc].lchild=Tree[loc].rchild=NULL;
10     return &Tree[loc++];
11 }
12 void postOrder(Node *T){//后序遍历 
13     if(T->lchild!=NULL){
14         postOrder(T->lchild);
15     }
16     if(T->rchild!=NULL){
17         postOrder(T->rchild);
18     }
19     printf("%d",T->c);
20 }
21 void inOrder(Node *T){//中序遍历 
22     if(T->lchild!=NULL){
23         postOrder(T->lchild);
24     }
25     printf("%d",T->c);
26     if(T->rchild!=NULL){
27         postOrder(T->rchild);
28     }    
29 }
30 void preOrder(Node *T){//先序遍历 
31     printf("%d",T->c);
32     if(T->lchild!=NULL){
33         postOrder(T->lchild);
34     }
35     if(T->rchild!=NULL){
36         postOrder(T->rchild);
37     }
38     
39 }
40 Node *Insert(Node *T,int x){
41     if(T==NULL){
42         T=create();
43         T->c=x;
44         return T;
45     }
46     else if(x<T->c){
47         T->lchild=Insert(T->lchild,x);
48     }
49     else if(x>T->c){
50         T->rchild=Insert(T->rchild,x);
51     }
52     return T;
53 }
54 int main(){
55     int n;
56     while(scanf("%d",&n)!=EOF){
57         loc=0;
58         Node *T=NULL;
59         for(int i=0;i<n;i++){
60             int x;
61             scanf("%d",&x);
62             T=Insert(T,x);
63         }
64         preOrder(T);
65         printf("\n");
66         inOrder(T);
67         printf("\n");
68         postOrder(T);
69         printf("\n");
70     }
71     return 0;
72 }

 

二叉排序树

标签:int   中序   order   ret   color   span   log   clu   pre   

原文地址:http://www.cnblogs.com/Elaine-DWL/p/6536187.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!