zoukankan      html  css  js  c++  java
  • 输入字符 回车结束输入 以树的形式进行输出

     1 #include <stdio.h>
     2 #include <stdlib.h>
     3 
     4 struct tree
     5 {
     6     char info;
     7     struct tree *left;
     8     struct tree *right;
     9 };
    10 
    11 struct tree *root;        /*树的第一个结点*/
    12 struct tree *construct(struct tree *root, struct tree *r, char info);
    13 void print(struct tree *r, int l);
    14 
    15 int main(void)
    16 {
    17     char s[80];
    18     root = NULL;
    19     do
    20     {
    21         printf("请输入一个字符:");
    22         gets(s);
    23         root = construct(root, root, *s);
    24     } while (*s);
    25     print(root, 0);
    26     getchar();
    27     return 0;
    28 }
    29 
    30 struct tree *construct(
    31 struct tree *root,
    32 struct tree *r,
    33     char info)
    34 {
    35     if (!r)
    36     {
    37         r = (struct tree *)malloc(sizeof(struct tree));
    38         if (!r)
    39         {
    40             printf("内存分配失败!");
    41             exit(0);
    42         }
    43         r->left = NULL;
    44         r->right = NULL;
    45         r->info = info;
    46         if (!root)
    47             return r;
    48         if (info < root->info)
    49             root->left = r;
    50         else
    51             root->right = r;
    52         return r;
    53     }
    54     if (info < r->info)
    55         construct(r, r->left, info);
    56     else
    57         construct(r, r->right, info);
    58 
    59     return root;
    60 }
    61 
    62 void print(struct tree *r, int l)
    63 {
    64     int i;
    65     if (!r)
    66         return;
    67     print(r->left, l + 1);
    68     for (i = 0; i < l; ++i)
    69         printf(" ");
    70     printf("%c
    ", r->info);
    71     print(r->right, l + 1);
    72 }
  • 相关阅读:
    高精度计算
    c++ sort
    算法分类小结
    二叉树层序遍历
    clion windows c++环境配置 mingw
    kafka,filebeat 配置
    centos7 源码安装mysql5.7
    如何优雅的生成及遍历python嵌套字典
    Java Swing 绝对布局管理方法,null布局【图】
    python3.4+pymssql 中文乱码问题解决
  • 原文地址:https://www.cnblogs.com/liugangjiayou/p/11670265.html
Copyright © 2011-2022 走看看