免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 5259 | 回复: 0
打印 上一主题 下一主题

[Linux] c语言 二叉树,为啥崩溃? [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2017-08-29 19:39 |只看该作者 |倒序浏览
  1. #include<stdio.h>
  2. #include<string.h>
  3. #include<stdlib.h>

  4. struct tree
  5. {
  6.   char* p_word;
  7.   int count;
  8.   struct tree* left;
  9.   struct tree* right;
  10. };

  11. int main()
  12. {
  13.   void output_tree(struct tree*);
  14.   void input_tree(struct tree*,char*);
  15.   struct tree* root=NULL;
  16.   //input
  17.   char* p=malloc(sizeof(char)*20);
  18.   setbuf(stdin,NULL);
  19.   scanf("%s",p);
  20.   while((*p)!='0')
  21.     {
  22.       input_tree(root,p);
  23.       setbuf(stdin,NULL);
  24.       p=malloc(20*sizeof(char));
  25.       scanf("%s",p);
  26.     }
  27.   //output
  28.   output_tree(root);
  29. }

  30. void input_tree(struct tree* root,char* p)
  31. {
  32.   if(root==NULL)
  33.     {
  34.       root=malloc(sizeof(struct tree));
  35.       root->p_word=p;
  36.       root->count=1;
  37.       root->left=root->right=NULL;
  38.     }
  39.   else if(strcmp(p,root->p_word)==0)
  40.     root->count++;
  41.   else if(strcmp(p,root->p_word)<0)
  42.     input_tree(root->left,p);
  43.   else if(strcmp(p,root->p_word)>0)
  44.     input_tree(root->right,p);
  45. }

  46. void output_tree(struct tree* root)
  47. {
  48.   if(root->left!=NULL)
  49.     output_tree(root->left);
  50.   if(root!=NULL)
  51.     printf("%s:%d\n",root->p_word,root->count);
  52.   if(root->right!=NULL)
  53.     output_tree(root->right);
  54. }
复制代码


您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP