数据结构实验之二叉树二:遍历二叉树(中序,后序)

Problem Description

已知二叉树的一个按先序遍历输入的字符序列,如abc,,de,g,,f,,, (其中,表示空结点)。请建立二叉树并按中序和后序的方式遍历该二叉树。

Input

连续输入多组数据,每组数据输入一个长度小于50个字符的字符串。

Output

每组输入数据对应输出2行:
第1行输出中序遍历序列;
第2行输出后序遍历序列。

 

Sample Input

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

Sample Output

cbegdfa
cgefdba

Hint

 

Source

xam

#include<bits/stdc++.h>
using namespace std;
struct node
{
    node *l,*r;
    char data;
};
char a[111];
int top;
node *creat()
{
    top++;
    node *root;
    root=new node;
    if(a[top]==',')
        root=NULL;
    else
    {
        root=new node;
        root->data=a[top];
        root->l=creat();
        root->r=creat();
    }
    return root;
}
void middleshow(node *root)
{
    if(root)
    {
        middleshow(root->l);
        cout<<root->data;
        middleshow(root->r);
    }
}
void finalshow(node *root)
{
    if(root)
    {
        finalshow(root->l);
        finalshow(root->r);
        cout<<root->data;
    }
}
int main()
{
    while(cin>>a)
    {
        top=-1;
        node *root;
        root=creat();
        middleshow(root);
        cout<<endl;
        finalshow(root);
        cout<<endl;
    }
    return 0;
}


/***************************************************
User name: ACM18171信科1801张林
Result: Accepted
Take time: 0ms
Take Memory: 252KB
Submit time: 2019-02-24 21:53:40
****************************************************/

猜你喜欢

转载自blog.csdn.net/weixin_43824158/article/details/87908525