zoukankan      html  css  js  c++  java
  • 九度oj 题目1184:二叉树遍历

    题目1184:二叉树遍历

    时间限制:1 秒

    内存限制:32 兆

    特殊判题:

    提交:4167

    解决:1690

    题目描述:

    编一个程序,读入用户输入的一串先序遍历字符串,根据此字符串建立一个二叉树(以指针方式存储)。
    例如如下的先序遍历字符串:
    ABC##DE#G##F###
    其中“#”表示的是空格,空格字符代表空树。建立起此二叉树以后,再对二叉树进行中序遍历,输出遍历结果。

    输入:

    输入包括1行字符串,长度不超过100。

    输出:

    可能有多组测试数据,对于每组数据,
    输出将输入字符串建立二叉树后中序遍历的序列,每个字符后面都有一个空格。
    每个输出结果占一行。

    样例输入:
    abc##de#g##f###
    样例输出:
    c b e g d f a 
    分析:如数据结构课本上有一个先序构建二叉树的伪代码,然而问题在于这样重复输入字符串构造二叉树,解决办法是一行一行读入
    字符串,当读入为空行时结束。读入的字符串在一个一个用来构造二叉树。
     1 #include <iostream>
     2 #include <cstdlib>
     3 #include <cstring>
     4 #include <cstdio>
     5 using namespace std;
     6 
     7 char str[101];
     8 int x;
     9  
    10 typedef struct node{
    11     char c;
    12     struct node *lchild, *rchild;
    13 }TNode, *Tree;
    14 
    15 //TNode* Creat(){
    16 //    if(str[x] == '#'){
    17 //        x++;
    18 //        return NULL;
    19 //    }
    20 //    TNode *T = new TNode;
    21 //    T->c = str[x++];
    22 //    T->lchild = Creat();
    23 //    T->rchild = Creat();
    24 //    return T;
    25 //}
    26 
    27 
    28 void Creat(Tree &T){
    29     if(str[x] == '#'){
    30         x++;
    31         T = NULL;
    32         return;
    33     }
    34     T = (TNode*)malloc(sizeof(TNode));//一定要开辟内存空间 
    35     T->c = str[x++];
    36     T->lchild = NULL;
    37     T->rchild = NULL;
    38     Creat(T->lchild);
    39     Creat(T->rchild);
    40     return;
    41 }
    42 
    43 
    44 void print(Tree T){
    45     if(T == NULL)
    46         return;
    47     print(T->lchild);
    48     printf("%c ", T->c);
    49     print(T->rchild);
    50 }
    51 
    52 int main(){
    53     while(gets(str)){
    54         x = 0;
    55         Tree T;
    56         //T = Creat();
    57         Creat(T);
    58         print(T);
    59         printf("
    ");
    60     }
    61     return 0;
    62 }
     
  • 相关阅读:
    (转)AWK函数
    (转)Linux ldconfig 与 ldd指令
    Linux内存管理Swap和Buffer Cache机制
    聚集索引和非聚集索引的区别有哪些
    mod_fastcgi和mod_fcgid的区别
    PHP运行模式
    详解php的安装模式---CGI,FASTCGI,php-fpm,mod_php,mod_cgi,mod_fcgid
    概念了解:CGI,FastCGI,PHP-CGI与PHP-FPM 各公共网关接口介绍
    PHP 5.3以上版本推荐使用mysqlnd驱动
    apache 静态编译和动态编译参考
  • 原文地址:https://www.cnblogs.com/qinduanyinghua/p/6535468.html
Copyright © 2011-2022 走看看