zoukankan      html  css  js  c++  java
  • SDUT 3344 数据结构实验之二叉树五:层序遍历

    数据结构实验之二叉树五:层序遍历

    Time Limit: 1000MS Memory Limit: 65536KB

    Problem Description

    已知一个按先序输入的字符序列,如abd,,eg,,,cf,,,(其中,表示空结点)。请建立二叉树并求二叉树的层次遍历序列。

    Input

     输入数据有多行,第一行是一个整数t (t<1000),代表有t行测试数据。每行是一个长度小于50个字符的字符串。

    Output

     输出二叉树的层次遍历序列。

    Example Input

    2
    abd,,eg,,,cf,,,
    xnl,,i,,u,,

    Example Output

    abcdefg
    xnuli

    DQE:

    先序序列建立二叉树后层序遍历,用到队列,可以使用数组简化代替,定义数组尺寸时注意假溢出即可,水题+1.

    附代码:
     1 #include <iostream>
     2 #include <cstdio>
     3 
     4 using namespace std;
     5 
     6 struct Tree
     7 {
     8     char c;
     9     Tree *lt,*rt;
    10 };
    11 
    12 Tree *creat(char *&xx)
    13 {
    14     if(*xx=='')
    15         return NULL;
    16     if(*xx==',')
    17     {
    18         xx++;
    19         return NULL;
    20     }
    21     Tree *r=new Tree;
    22     r->c=*xx++;
    23     r->lt=creat(xx);
    24     r->rt=creat(xx);
    25     return r;
    26 }
    27 
    28 void cxvisit(Tree *r)
    29 {
    30     Tree *que[100];
    31     int i=0,j=0;
    32     que[j++]=r;
    33     while(i<j)
    34     {
    35         if(que[i])
    36         {
    37             que[j++]=que[i]->lt;
    38             que[j++]=que[i]->rt;
    39             printf("%c",que[i]->c);
    40         }
    41         i++;
    42     }
    43 }
    44 
    45 int main()
    46 {
    47     Tree *root;
    48     int n;
    49     scanf("%d",&n);
    50     char xx[55],*p;
    51     while(n--)
    52     {
    53         p=xx;
    54         scanf("%s",xx);
    55         root=creat(p);
    56         cxvisit(root);
    57         printf("
    ");
    58     }
    59     return 0;
    60 }
    61 
    62 /***************************************************
    63 User name: ***
    64 Result: Accepted
    65 Take time: 0ms
    66 Take Memory: 156KB
    67 Submit time: 2016-11-03 18:35:52
    68 ****************************************************/
  • 相关阅读:
    哇,博客开通啦
    前端与后端数据交互的方式之ajax
    apply()方法和call()方法
    元素居中的方法
    JS中兼容问题的汇总
    关于元素尺寸问题的汇总
    小案例之随机点名系统
    圣杯布局与双飞翼布局
    js自动分页加载所有数据
    浏览器工作流程
  • 原文地址:https://www.cnblogs.com/Leroscox/p/6031410.html
Copyright © 2011-2022 走看看