题目1184:二叉树遍历

来源:互联网 发布:大连中日红软件 编辑:程序博客网 时间:2024/06/10 03:38

描述:

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

输入:

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

输出:

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

样例输入:

abc##de#g##f###

样例输出:

c b e g d f a

#include<iostream>#include<string.h>#include<stdlib.h>using namespace std;char ch[200];int c;//ch下标int len;typedef struct BiTNode{    char data;    struct BiTNode *lchild;    struct BiTNode *rchild;}BiTNode, *BiTree;void create(BiTree *t){    if (ch[c] == '#'){        *t = NULL;        return;    }    *t = (BiTree)malloc(sizeof(BiTNode));      (*t)->data = ch[c++];     create(&(*t)->lchild);    c++;    create(&(*t)->rchild);}void inorder(BiTree t){    if (t){        inorder(t->lchild);        cout << t->data << " ";        inorder(t->rchild);    }}void destory(BiTree *t){    if (*t){        destory(&(*t)->lchild);        destory(&(*t)->rchild);        delete *t;    }}int main(){//  freopen("in.txt", "r", stdin);    while (cin >> ch){        BiTree T;        c = 0;        len = strlen(ch);        create(&T);        inorder(T);        destory(&T);        cout << endl;    }//  fclose(stdin);//  freopen("CON", "r", stdin);//  system("pause");    return 0;}
0 0
原创粉丝点击