1340:【例3-5】扩展二叉树
信息学奥赛一本通【1340:【例3-5】扩展二叉树】详细讲解
扩展二叉树(#号法)先序和后续可确定二叉树,中序不可
C++参考代码一:
/*
1340:【例3-5】扩展二叉树-课本上代码
http://ybt.ssoier.cn:8088/problem_show.php?pid=1340
https://blog.csdn.net/weixin_44270812/article/details/100585600
*/
#include <iostream>
#include <stdlib.h>
#include <string>
#include <cstring>
#include <algorithm>
#include <cstdio>
using namespace std;
typedef struct node;
typedef node *tree;
struct node
{
char data;
tree lchild, rchild;
};
tree bt;
int i;
string s;
void build(tree &bt) //建树
{
if(s[++i]!='.')
{
//bt = new node;
bt = new node;
bt->data = s[i];
build(bt->lchild);
build(bt->rchild);
}
else bt = NULL;
}
/*
【输入样例】tree_b.in
ABD..EF..G..C..
【输出样例】tree_b.out
DBFEGAC
DFGEBCA
*/
//输出中序序列
void printzx(tree bt)
{
if( bt )
{
printzx(bt->lchild);
cout << bt->data;
printzx(bt->rchild);
}
}
void printhx(tree bt) //输出后序序列
{
if( bt )
{
printhx(bt->lchild);
printhx(bt->rchild);
cout << bt->data;
}
}
int main( void )
{
//freopen("tree_b.in", "r", stdin);
//freopen("tree_b.out", "w", stdout);
cin >> s;
i = -1;
build(bt);
//中序遍历
printzx(bt);
cout << endl;
//后序遍历
printhx(bt);
cout << endl;
return 0;
}
C++参考代码二:
/*
1340:【例3-5】扩展二叉树01
http://ybt.ssoier.cn:8088/problem_show.php?pid=1340
*/
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
using namespace std;
string s;
int i,a[1000],l[1000],r[1000];
void build(int k)
{
i++;
if ( l[k]==0 )
l[k]=i;
else
r[k]=i;
int m;
m=i;
if ( s[i-1]!='.' )
{
build(m);
build(m);
}
}
void printzx(int k)
{
if (s[k-1]=='.') return;
else
{
printzx( l[k] );
cout<<s[k-1];
printzx( r[k] );
}
}
void printhx(int k)
{
if (s[k-1]=='.') return;
else
{
printhx( l[k] );
printhx( r[k] );
cout<<s[k-1];
}
}
int main( void )
{
cin>>s;
i=1;
build(1);
build(1);
//中序遍历
printzx(1);
cout<<endl;
//后序遍历
printhx(1);
cout<<endl;
return 0;
}
C++参考代码三:
/*
1340:【例3-5】扩展二叉树02
http://ybt.ssoier.cn:8088/problem_show.php?pid=1340
*/
#include <iostream>
using namespace std;
#include <cstdio>
char s[2555];
int i=-1;
struct tree
{
char a;
tree *lchild,*rchild;
};
tree *root,*tzx,*thx;
//ABD..EF..G..C..
tree *build()
{
i++;
tree *reft;
if (s[i]!='.')
{
reft=new tree;
reft->a=s[i];
//建立左子树
reft->lchild=build();
//建立右子树
reft->rchild=build();
}
else reft=NULL;
return reft;
}
//中序
void printzx(tree *twork)
{
if ( twork != NULL )
{
printzx(twork->lchild);
cout<<twork->a;
printzx(twork->rchild);
}
}
//后序
void printhx(tree *twork)
{
if ( twork != NULL )
{
printhx(twork->lchild);
printhx(twork->rchild);
cout<<twork->a;
}
}
int main( void )
{
cin>>s;
//建立扩展二叉树
root=build();
//中序遍历
printzx(root);
cout<<endl;
//后序遍历
printhx(root);
return 0;
}
【洛谷比赛】洛谷入门赛 #11
NOI 大纲(2023年修订版)正式发布
中小学信息学相关比赛汇总(C++类)
信息学竞赛有什么好的比赛网站?
信息学竞赛有什么好的比赛网站?_信息学奥赛一本通(c++版)在线评测系统_dllglvzhenfeng的博客-CSDN博客
高含金量国际计算机编程竞赛
【国际竞赛-计算机篇】2022年高含金量的计算机竞赛有哪些
【国际竞赛-计算机篇】2022年高含金量的计算机竞赛有哪些_计算机竞赛含金量排名_dllglvzhenfeng的博客-CSDN博客
信息学奥赛寒假、暑假、国庆十一假期 如何进行集训
信息学奥赛学习、训练、测试的顺序,思路及方法