【题目来源】
https://www.acwing.com/problem/content/3387/
【题目描述】
编写一个程序,读入用户输入的一串先序遍历字符串,根据此字符串建立一个二叉树(以指针方式存储)。
例如如下的先序遍历字符串:abc##de#g##f###,其中 # 表示的是空格,空格字符代表空树。
建立起此二叉树以后,再对二叉树进行中序遍历,输出遍历结果。
【输入格式】
共一行,包含一个字符串,表示先序遍历字符串。
【输出格式】
共一行,输出将输入字符串建立二叉树后中序遍历的序列,字符之间用空格隔开。
注意,输出中不用包含 #。
【数据范围】
输入字符串长度不超过 100,且只包含小写字母和 #。
【输入样例】
abc##de#g##f###
【输出样例】
c b e g d f a
【算法分析】
本题是按输入的先序遍历序列建树,然后输出对应的中序遍历序列。
若调整如下“大犇代码”中的如下三句代码的顺序,便可输出对应的先序遍历序列、中序遍历序列、后序遍历序列。
//PreOrder
cout<<ch<<" ";
dfs();
dfs();
//InOrder
dfs();
cout<<ch<<" ";
dfs();
//PostOrder
dfs();
dfs();
cout<<ch<<" ";
【大犇代码】
#include <bits/stdc++.h>
using namespace std;
void dfs(){
char ch=getchar();
if(ch=='#') return;
dfs();
cout<<ch<<" ";
dfs();
}
int main() {
dfs();
return 0;
}
/*
in:
abc##de#g##f###
out:
c b e g d f a
*/
【传统代码】
#include <bits/stdc++.h>
using namespace std;
struct BiTNode {
char data;
BiTNode *lchild,*rchild;
};
typedef struct BiTNode *BiTree;
void CreateBiTree(BiTree &T) {//按先序遍历的顺序建立二叉链表
char ch;
cin>>ch;
if(ch=='#') T=NULL;
else {
T=new BiTNode;
T->data=ch;
CreateBiTree(T->lchild);
CreateBiTree(T->rchild);
}
}
void InOrderTraverse(BiTree T) {//中序遍历
if(T) {
InOrderTraverse(T->lchild);
cout<<T->data<<" ";
InOrderTraverse(T->rchild);
}
}
int main() {
BiTree tree;
CreateBiTree(tree);
InOrderTraverse(tree);
cout<<endl;
return 0;
}
/*
in:
ABD#G###CE##F##
out:
D G B A E C F
*/
【参考文献】
https://blog.csdn.net/hnjzsyjyj/article/details/127290036
https://www.acwing.com/solution/content/183211/
https://www.acwing.com/solution/content/64837/