C - 二叉树的输入

Description

用二叉树的带虚结点表示的前序遍历序可以唯一的确定一棵二叉树。

Input

输入包含多组数据。
每行是一棵二叉树的带虚结点(#)表示的前序遍历序串,长度不超过2000。每个结点为一个字符。

Output

对每行输入,输出对应二叉树的中序遍历序(不含虚结点)、后序遍历序(不含虚结点)和层次遍历序(不含虚结点)。
每棵二叉树的输出占一行,中序遍历序、后序遍历序和层次遍历序之间用一个空格隔开。

Sample Input
ab##c##
#
ab###

Sample Output
bac bca abc

ba ba ab

代码:

/*
需要注意的是
输入 字符串的时候,不能用 scanf 或者是 gets 输入,只能用 cin 输入
原因是:
cin不接受空格,TAB,换行符 等键的输入,遇到这些键,字符串会终止
而gets()则接受连续的输入,包括空格,TAB
在每一行的最后有个换行符
*/

----------
#include<stdio.h>
#include<string.h>
#include<cstring>
#include<stdlib.h>
#include<iostream>
#include<queue>
using namespace std;
char c;
typedef struct BiTNode
{
    char data;
    struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
void CreateBiTree(BiTree &T,int flag)
{
    if(flag)//每一组时,当 flag 不是 1 的时候,允许输入下一个字符
        cin>>c;
    else
        flag=1;//输入第一个字符的时候,flag是0,然后就变成1 ,去输入下一个字符
    if(c=='\n')
        return ;
    else{
        if(c=='#')
            T=NULL;
        else{
            T=(BiTree)malloc(sizeof(BiTNode));
            T->data=c;
            CreateBiTree(T->lchild,flag);
            CreateBiTree(T->rchild,flag);
        }
    }
}
void Visit(BiTree T)
{
    if(T->data!='#')
        printf("%c",T->data);
}
void Inorder(BiTree T)
{
    if(T!=NULL)
    {
        Inorder(T->lchild);
        Visit(T);
        Inorder(T->rchild);

    }
}
void Postorder(BiTree T)
{
    if(T!=NULL)
    {
        Postorder(T->lchild);
        Postorder(T->rchild);
        Visit(T);
    }
}
void Levelorder(BiTree T)//层次遍历
{
    BiTree p=T;
    queue<BiTree> q;
    q.push(p);
    while(!q.empty())
    {
        p=q.front();
        printf("%c",p->data);
        q.pop();
        if(p->lchild!=NULL)
            q.push(p->lchild);
        if(p->rchild!=NULL)
            q.push(p->rchild);
    }
}
int main()
{
    while(cin>>c)
    {
        int flag=0;
        BiTree T;
        if(c=='#')//特别考虑样例二的情况
            cout<<endl;
        else{
            flag=0;
            CreateBiTree(T,flag);
            Inorder(T);
            printf(" ");
            Postorder(T);
            printf(" ");
            Levelorder(T);
            cout<<endl;
        }
        getchar();//用来取每一行最后输出是的换行符
    }
}

猜你喜欢

转载自blog.csdn.net/jkdd123456/article/details/80209557