题目:扩展二叉树(树的基本操作)
·
题目:扩展二叉树
题目描述
由于先序、中序和后序序列中的任一个都不能唯一确定一棵二叉树,所以对二叉树做如下处理,将二叉树的空结点用·补齐,如图所示。我们把这样处理后的二叉树称为原二叉树的扩展二叉树,扩展二叉树的先序和后序序列能唯一确定其二叉树。现给出扩展二叉树的先序序列,要求输出其中序和后序序列。
输入输出格式
输入格式:
无
输出格式:
无
输入输出样例
输入样例#1:
ABD..EF..G..C..
输出样例#1:
DBFEGAC
DFGEBCA
提示信息
提示就是没有提示AWA
题目分析
这一题其实考的就是对树的相关操作,这里来简单的归纳一下
树的结构储存:
typedef struct node;
typedef node*tree;
struct node{
char data;
tree lchild,rchild;
}*root;
建立一棵树:
void build(tree&bt){
if(a[++i]!='.'){ // .代表空树
bt=new node;
bt->data=a[i];
build(bt->lc);
build(bt->rc);
}else bt=NULL;
}
删除一颗树:
void dis(tree&bt){
if(bt){
dis(bt->lc);
dis(bt->rc);
delete bt;
}
}
先序遍历:
void print_x(tree&bt){
if(bt){
cout<<bt->data;
print_z(bt->lc);
print_z(bt->rc);
}
}
中序遍历:
void print_z(tree&bt){
if(bt){
print_z(bt->lc);
cout<<bt->data;
print_z(bt->rc);
}
}
后序遍历:
void print_h(tree&bt){
if(bt){
print_h(bt->lc);
print_h(bt->rc);
cout<<bt->data;
}
}
这样,所有的操作就一目了然啦awa~
既然这样,那源代码自然也就很清晰了:
#include<iostream>
using namespace std;
typedef struct node;
typedef node*tree;
struct node{
char data;
tree lc,rc;
}*root;
string a;
int i = -1;
void build(tree&bt){
if(a[++i]!='.'){
bt=new node;
bt->data=a[i];
build(bt->lc);
build(bt->rc);
}else bt=NULL;
}
void dis(tree&bt){
if(bt){
dis(bt->lc);
dis(bt->rc);
delete bt;
}
}
void print_x(tree&bt){
if(bt){
cout<<bt->data;
print_z(bt->lc);
print_z(bt->rc);
}
}
void print_z(tree&bt){
if(bt){
print_z(bt->lc);
cout<<bt->data;
print_z(bt->rc);
}
}
void print_h(tree&bt){
if(bt){
print_h(bt->lc);
print_h(bt->rc);
cout<<bt->data;
}
}
int main(){
cin>>a;
build(root);
print_z(root);
cout<<endl;
print_h(root);
cout<<endl;
return 0;
}
更多推荐

所有评论(0)