二叉树遍历1
描述
编一个程序,读入用户输入的一串先序遍历字符串,根据此字符串建立一个二叉树(以指针方式存储)。 例如如下的先序遍历字符串: ABC##DE#G##F### 其中“#”表示的是空格,空格字符代表空树。建立起此二叉树以后,再对二叉树进行中序遍历,输出遍历结果。
输入描述:
输入包括1行字符串,长度不超过100。
输出描述:
可能有多组测试数据,对于每组数据, 输出将输入字符串建立二叉树后中序遍历的序列,每个字符后面都有一个空格。 每个输出结果占一行。
示例:
输入:
abc##de#g##f###
输出:
c b e g d f a
#include<bits/stdc++.h>
using namespace std;
//二叉树遍历1
struct treenode{
char data;
treenode * leftchild;
treenode * rightchild;
//新节点的构造函数
treenode(char ch): data(ch),leftchild(NULL),rightchild(NULL){}
};
treenode * create(string str,int& position){
char ch = str[position++];
if(ch=='#')return NULL;//返回空树
treenode * root = new treenode(ch);//建立新节点
root->leftchild = create(str,position);
root->rightchild = create(str,position);
return root;
}
//中序遍历
void InOrder(treenode *root){
if(root==NULL){
return;
}
InOrder(root->leftchild);
cout<<root->data<<' ';
InOrder(root->rightchild);
}
int main(){
string str;
//输入前序遍历
while(cin>>str){
int position=0;
treenode *root=create(str,position);//root为根结点
InOrder(root);
}
return 0;
}
二叉树遍历2
描述
二叉树的前序、中序、后序遍历的定义: 前序遍历:对任一子树,先访问根,然后遍历其左子树,最后遍历其右子树; 中序遍历:对任一子树,先遍历其左子树,然后访问根,最后遍历其右子树; 后序遍历:对任一子树,先遍历其左子树,然后遍历其右子树,最后访问根。 给定一棵二叉树的前序遍历和中序遍历,求其后序遍历(提示:给定前序遍历与中序遍历能够唯一确定后序遍历)。
输入描述:
两个字符串,其长度n均小于等于26。 第一行为前序遍历,第二行为中序遍历。 二叉树中的结点名称以大写字母表示:A,B,C…最多26个结点。
输出描述:
输入样例可能有多组,对于每组测试样例, 输出一行,为后序遍历的字符串。
示例:
输入:
ABC
BAC
FDXEAG
XDEFAG
输出:
BCA
XEDGAF
#include<bits/stdc++.h>
using namespace std;
//二叉树遍历2
struct treenode{
char data;
treenode* leftchild;
treenode* rightchild;
treenode(char ch):data(ch),leftchild(NULL),rightchild(NULL){}
};
treenode*create(string str1,string str2){
if(str1.length()==0){
return NULL;//空树
}
char ch;
ch=str1[0];//前序遍历的"根"结点
treenode*root=new treenode(ch);
int position=str2.find(ch);//找到中序遍历的根结点所在位置
root->leftchild=create(str1.substr(1,position),str2.substr(0,position));
//substr()的第二个参数表示的是个数
root->rightchild=create(str1.substr(position+1),str2.substr(position+1));
return root;
}
//后序遍历
void PostOrder(treenode * root){
if(root==NULL){
return;
}
PostOrder(root->leftchild);
PostOrder(root->rightchild);
cout<<root->data;
}
int main(){
string str1,str2;
//str1是前序遍历
//str2是后序遍历
while(cin>>str1>>str2){
treenode * root = create(str1,str2);
//后序遍历
PostOrder(root);
cout<<endl;
}
return 0;
}