扩展二叉树

来源:互联网 发布:淘宝用户画像怎么做 编辑:程序博客网 时间:2024/06/10 17:28

【例3-5】扩展二叉树


时间限制: 1000 ms         内存限制: 65536 KB
 

【题目描述】

由于先序、中序和后序序列中的任一个都不能唯一确定一棵二叉树,所以对二叉树做如下处理,将二叉树的空结点用·补齐,如图所示。我们把这样处理后的二叉树称为原二叉树的扩展二叉树,扩展二叉树的先序和后序序列能唯一确定其二叉树。

现给出扩展二叉树的先序序列,要求输出其中序和后序序列。

【输入】

扩展二叉树的先序序列。

【输出】

输出其中序和后序序列。

【输入样例】

ABD..EF..G..C..

【输出样例】

DBFEGACDFGEBCA

【来源】


 
#include<iostream>#include<string>#include<cstring>#include<algorithm>using namespace std;typedef struct node;typedef node *tree;//tree相当于node struct node{//一个节点包括数据域,左右孩子 char data;treelchild,rchild;};tree bt;int i;string s;void build(tree &bt)//建树{if(s[++i]!='.'){bt=new node;bt->data=s[i];build(bt->lchild);build(bt->rchild);}else bt=NULL;} 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(){//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;}


原创粉丝点击