• sdut 2136 数据结构实验之二叉树的建立与遍历(二叉树遍历,叶子数和深度)


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

    Time Limit: 1000MS Memory limit: 65536K

    题目描述

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

    输入

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

    输出

    输出共有4行:
    第1行输出中序遍历序列;
    第2行输出后序遍历序列;
    第3行输出叶子节点个数;
    第4行输出二叉树深度。

    示例输入

    abc,,de,g,,f,,,

    示例输出

    cbegdfa
    cgefdba
    3
    5
    View Code
     1 #include<stdio.h>
     2 #include<string.h>
     3 #include<stdlib.h>
     4 typedef struct node
     5 {
     6     char c;
     7     struct node *l, *r;
     8 }tree;
     9 char str[1001];
    10 int i;
    11 tree *build()
    12 {
    13     tree *p;
    14     if(str[i] == ',')
    15     {
    16         i ++;
    17         return NULL;
    18     }
    19     p = (tree *)malloc(sizeof(tree));
    20     p -> c = str[i];
    21     i++;
    22     p -> l = build();
    23     p -> r = build();
    24     return p;
    25 }
    26 void midsearch(tree *head)
    27 {
    28     if(head == NULL)
    29     return ;
    30     midsearch(head -> l);
    31     printf("%c",head -> c);
    32     midsearch(head -> r);
    33 }
    34 void lastsearch(tree *head)
    35 {
    36     if(head == NULL)
    37     return ;
    38     lastsearch(head -> l);
    39     lastsearch(head -> r);
    40     printf("%c",head -> c);
    41 }
    42 int leafs(tree *head)
    43 {
    44     if(head == NULL)
    45     return 0;
    46     if(head -> l == NULL && head -> r == NULL)
    47     return 1;
    48     else
    49     return (leafs(head ->l) + leafs(head -> r));
    50 }
    51 int deep(tree *head)
    52 {
    53     int m, n;
    54     if(head == NULL)
    55     return 0;
    56     m = deep(head -> l);
    57     n = deep(head -> r);
    58     if(m > n)
    59     return m+1;
    60     else
    61     return n+1;
    62 }
    63 int main()
    64 {
    65     tree *head;
    66     int leaf;
    67     gets(str);
    68     i=0;
    69     head = build();
    70     midsearch(head);
    71     puts("");
    72     lastsearch(head);
    73     puts("");
    74     leaf = leafs(head);
    75     printf("%d\n",leaf);
    76     printf("%d\n",deep(head));
    77     return 0;
    78 }
  • 相关阅读:
    转 linux设备模型(4)
    SQL convert
    SQL 中的 case when
    自己写的文本文件加密器
    [A3] 2D Airfoil Aerodynamic Analysis With Fluent & Gambit
    [A2]更快的使用你的键盘:AutoHotkey
    [A4]更快的使用你的键盘:AutoHotkey(2)
    开篇HOG提取训练检测+样本制作
    Flash调用Lua脚本: 五
    Sql Server全局变量 【转载】
  • 原文地址:https://www.cnblogs.com/wanglin2011/p/2609979.html
Copyright © 2020-2023  润新知