此题需要借助栈来实现。不过栈中元素是二叉树结点的指针。两个栈,一个辅助栈,一个用来保留当前最长路径中的结点的栈。可见注释……当然,也可以递归求解,如下:
#include<bits/stdc++.h>//递归求解
using namespace std;
const int maxn=1000;
typedef struct node
{
char data;
struct node *lc,*rc;
} node,*link;
int i,flag;
char path[1000],longpath[1000];
void creat(link &L)
{
char ch;
scanf("%c",&ch);
i++;
if(i==1&&ch=='0')
{
flag=0;
return ;
}
if(ch=='0')
L=NULL;
else
{
L=new node;
L->data=ch;
creat(L->lc);
creat(L->rc);
}
}
void pathlongest(link L,char path[],int &pathlen,char longpath[],int &longth)
{
if(L)
{
if(L->lc==NULL&&L->rc==NULL)
{
path[pathlen]=L->data;
if(pathlen>longth)
{
for(int i=0;i<=pathlen;i++)
longpath[i]=path[i];
longth=pathlen;
}
}
else
{
path[pathlen++]=L->data;
pathlongest(L->lc,path,pathlen,longpath,longth);
pathlongest(L->rc,path,pathlen,longpath,longth);
pathlen--;
}
}
}
int main()
{
while(1)
{
i=0,flag=1;
link L;
creat(L);
if(!flag) break;
int longth=0,pathlen=0;
pathlongest(L,path,pathlen,longpath,longth);
printf("%d\n",longth+1);
for(int i=0;i<=longth;i++) printf("%c",longpath[i]);
printf("\n");
getchar();
}
return 0;
}
#include<bits/stdc++.h>
using namespace std;
const int maxn=1000;
typedef struct node
{
char data;
struct node *lc,*rc;
} node,*link;
int i,flag;
void creat(link &L)
{
char ch;
scanf("%c",&ch);
i++;
if(i==1&&ch=='0')
{
flag=0;
return ;
}
if(ch=='0')
L=NULL;
else
{
L=new node;
L->data=ch;
creat(L->lc);
creat(L->rc);
}
}
void path(link L)
{
link p=L,l[maxn],s[maxn];//l,s是栈,元素是二叉树结点的指针,l中保留当前路径中的结点
int top=0,tag[maxn],longest=0;
while(p||top>0)
{
while(p)//沿左分枝向下
{
s[++top]=p;
tag[top]=0;
p=p->lc;
}
if(tag[top]==1)//当前结点的友分枝已遍历
{
if(!s[top]->lc&&!s[top]->rc)//只有到叶子结点才查看路径长度
{
if(top>longest)//更新
{
for(int j=1;j<=top;j++) l[j]=s[j];
longest=top;
}
}
top--;//保留当前最长路径到l栈,记住最高栈顶指针,退栈
}
else if(top>0)//沿右子分枝向下
{
tag[top]=1;
p=s[top]->rc;
}
}
printf("%d\n",longest);
for(int k=1;k<=longest;k++)
printf("%c",l[k]->data);
printf("\n");
}
int main()
{
while(1)
{
i=0,flag=1;
link L;
creat(L);
if(!flag) break;
path(L);
getchar();
}
return 0;
}