binary tree

  1 #include <stdio.h>
  2 #include <stdlib.h>
  3 
  4 typedef struct tnode{
  5         int data;
  6         struct tnode *left;
  7         struct tnode *right;
  8 }tnode,*tree;
  9 
 10 void createtree(tree *t,int d){
 11         tnode *tn=(tnode *)malloc(sizeof(tnode));
 12         tnode ** root;
 13         (*tn).data = d;
 14         (*tn).right = 0;
 15         (*tn).left = 0;
 16         if(!(*t)){
 17                 *t = tn;
 18                 root = *t;
 19         }
 20         else{
 21         root = *t;
 22                 while(1){
 23                         if((**t).data < d){
 24                                 if((**t).right){
 25                                         *t = (**t).right;
 26                                         continue;
 27                                 }
 28                                 else{
 29                                         (**t).right = tn;
 30                                         break;
 31                                 }
 32                         }
 33                         else if((**t).data >= d){
 34                                 if((**t).left){
 35                                         *t =(**t).left;
 36                                         continue;
 37                                 }
 38                                 else{
 39                                         (**t).left = tn;
 40                                         break;

 41                                 }
 42                         }
 43                 }
 44         }
 45         *t = root;
 46 }
 47 void inorder(tree t)
 48 {
 49         if(t){
 50                 inorder((*t).left);
 51                 printf("%d\n",(*t).data);
 52                 inorder((*t).right);
 53         }
 54 }
 55 void main()
 56 {
 57         int i;
 58         tree t=0;
 59         printf("input number:0 exit\n");
 60         scanf("%d",&i);
 61         while(i != 0){
 62                 createtree((&t),i);
 63                 scanf("%d",&i);
 64         }
 65         printf("the data is:\n");
 66         inorder(t);
 67         printf("\n");
 68 }

posted on 2012-05-27 15:45 三少_爷 阅读(114) 评论(0)  编辑 收藏 引用 所属分类: the c programming language


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


<2012年5月>
293012345
6789101112
13141516171819
20212223242526
272829303112
3456789

导航

统计

常用链接

留言簿

随笔分类

随笔档案

My Website

搜索

最新评论

阅读排行榜

评论排行榜