09-二叉树遍历-
题目描述
给定一颗二叉树的逻辑结构如下图,(先序遍历的结果,空树用字符‘0’表示,例如AB0C00D00),建立该二叉树的二叉链式存储结构。
编写程序输出该树的所有叶子结点和它们的父亲结点
输入
第一行输入一个整数t,表示有t个二叉树
第二行起,按照题目表示的输入方法,输入每个二叉树的先序遍历,连续输入t行
输出
第一行按先序遍历,输出第1个示例的叶子节点
第二行输出第1个示例中与叶子相对应的父亲节点
以此类推输出其它示例的结果
输入样例
3
AB0C00D00
AB00C00
ABCD0000EF000
C D
B A
B C
A A
D F
C E
#include<iostream>
using namespace std;
class btnode
{
public:
char data;
btnode *lchild;
btnode *rchild;
btnode():lchild(NULL),rchild(NULL){}
~btnode(){}
};
class bitree
{
btnode *root;
int pos;
string strtree;
char father[20];
int pf;
btnode *createbitree()
{
btnode *T;
char ch;
ch=strtree[pos++];
if(ch=='0')
T=NULL;
else
{
T=new btnode();
T->data=ch;
T->lchild=createbitree();
T->rchild=createbitree();
}
return T;
}
void show(btnode *t,char f)//叶子结点&父亲结点查找
{
if(t)
{
if(t->lchild==NULL&&t->rchild==NULL)//为叶子结点
{
cout<<t->data<<" ";
father[pf++]=f;
}
show(t->lchild,t->data);//t->lchild的父亲结点为t->data
show(t->rchild,t->data);
}
}
public:
bitree(){};
~bitree(){};
void createbitree(string treearray)
{
pos=0;
strtree.assign(treearray);
root=createbitree();
}
void show()
{
pos=0;pf=0;
show(root,root->data);//输出叶子结点
cout<<endl;
int len=strlen(father);
for(int i=0;i<len;i++)
cout<<father[i]<<" ";
cout<<endl;
}
};
int main()
{
int t;
cin>>t;
while(t--)
{
string tree;
bitree T;
cin>>tree;
T.createbitree(tree);
T.show();
}
return 0;
}