• SDUT2136数据结构实验之二叉树的建立与遍历


    题目描述

           已知一个按先序序列输入的字符序列,如abc,,de,g,,f,,,(其中逗号表示空节点)。请建立二叉树并按中序和后序方式遍历二叉树,最后求出叶子节点个数和二叉树深度。

    输入

     输入一个长度小于50个字符的字符串。

    输出

    输出共有4行:
    第1行输出中序遍历序列;
    第2行输出后序遍历序列;
    第3行输出叶子节点个数;
    第4行输出二叉树深度。
     
    对于严老师书上写的那些 表示 看得真的很吃力 换了本书 网上搜搜 东凑西凑 总算把这个题写出来了
     1 #include<stdio.h>
    2 #include<malloc.h>
    3 typedef struct btnode
    4 {
    5 char data;
    6 struct btnode *L,*R;
    7 }st;
    8 st *t;
    9 int count = 0 ;
    10 st *creat(st *t)//递归创建二叉树
    11 {
    12 char c;
    13 if((c = getchar())==',')//空节点
    14 t = NULL;
    15 else
    16 {
    17 t = (st *)malloc(sizeof(st));
    18 t->data = c;//先序建立
    19 t->L = creat(t->L);
    20 t->R = creat(t->R);
    21 }
    22 return t;
    23 }
    24 void inorder(st *t)//中序遍历
    25 {
    26 if(t!=NULL)
    27 {
    28 inorder(t->L);
    29 printf("%c",t->data);
    30 inorder(t->R);
    31 }
    32 }
    33 void posorder(st *t)//后序遍历
    34 {
    35 if(t!=NULL)
    36 {
    37 posorder(t->L);
    38 posorder(t->R);
    39 printf("%c",t->data);
    40 }
    41 }
    42 void leafnum(st *t)//递归求叶子数
    43 {
    44 if(t)
    45 {
    46 if((t->L == NULL)&&(t->R == NULL))
    47 count++;
    48 leafnum(t->L);
    49 leafnum(t->R);
    50 }
    51 }
    52 int deep(st *t)
    53 {
    54 int ld,rd;
    55 if(!t)
    56 return 0;
    57 else
    58 {
    59 ld = deep(t->L);
    60 rd = deep(t->R);
    61 if(ld>=rd)
    62 return ld+1;
    63 else
    64 return rd+1;
    65 }
    66 return 1;
    67 }
    68 int main()
    69 {
    70 struct btnode *s;
    71 int height ;
    72 s = creat(t);
    73 inorder(s);
    74 puts("");
    75 posorder(s);
    76 puts("");
    77 leafnum(s);
    78 printf("%d\n",count);
    79 height = deep(s);
    80 printf("%d\n",height);
    81 return 0;
    82 }
    都是递归求的 写的也迷迷糊糊
     
  • 相关阅读:
    用C#编写获取远程IP,MAC的方法
    创建 TransactSQL 作业步骤
    S3C2440系统时钟
    C# 跟年月日判断星期几
    嵌入式系统启动例程
    使用HTML5和CSS3来创建幻灯片
    巧解Android时区加载过慢的问题
    HTML5之美
    C#如何取硬件标志
    S3C2440看门狗定时器(Watchdog)
  • 原文地址:https://www.cnblogs.com/shangyu/p/2365290.html
Copyright © 2020-2023  润新知