#include <iostream>
using namespace std;
int maxi=0;int m=0,n=0;
typedef struct BiTNode
{
char data;
struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;BiTree temp;
void CreateBiTree(BiTree &T)
{
char ch;
cin>>ch;
if(ch=='0')T=NULL;
else
{
T=new BiTNode;
T->data=ch;
CreateBiTree(T->lchild);
CreateBiTree(T->rchild);
}
}
void CreateBiTree(BiTree &T,char ch)
{
if(ch=='0')T=NULL;
else
{
T=new BiTNode;
T->data=ch;
CreateBiTree(T->lchild);
CreateBiTree(T->rchild);
}
}
int Traverse(BiTree T)
{
if(T)
{
m++;
if(m>maxi)
{
maxi=m;
temp=T;
}
// cout<<T->data<<":"<<m<<endl;
Traverse(T->lchild);
Traverse(T->rchild);
m--;
}
}
int AllPath(BiTree T,char path[],int pathlen)
{
int i;
if(T!=NULL)
{
if(T->lchild==NULL && T->rchild==NULL)
{
//cout<<" "<<T->data<<"到根结点路径:";
cout<<T->data;
for(i=pathlen-1;i>=0;i--)
cout<<path[i];
cout<<endl;
}
else
{
path[pathlen]=T->data;
pathlen++;
AllPath(T->lchild,path,pathlen);
AllPath(T->rchild,path,pathlen);
pathlen--;
}
}
}
int main()
{
while(1)
{
char ch;char path[100];int pathlen=0;
cin>>ch;
if(ch=='0')break;
BiTree T;
CreateBiTree(T,ch);
Traverse(T);
//cout<<maxi<<endl;
AllPath(T,path,pathlen);
maxi=0;m=0;
}
return 0;
}
描述
设二叉树中每个结点的元素均为一个字符,按先序遍历的顺序建立二叉链表,编写算法求出每个叶子结点到根结点的路径。
输入
多组数据。每组数据一行,为二叉树的先序序列(序列中元素为‘0’时,表示该结点为空)。当输入只有一个“0”时,输入结束。
输出
每组数据输出n行(n为叶子结点的个数),每行为一个叶子结点到根节点的路径(按照叶子结点从左到右的顺序)。
输入样例 1
abcd00e00f00ig00h00
abd00e00cf00g00
0
输出样例 1
dcba
ecba
fba
gia
hia
dba
eba
fca
gca