建立二叉树并找第一条最长的路径长度,但程序最后只能输出最后插入的树的结点的值。求解原因是什么,怎么在原基础上修改,在此感激不尽
#include <iostream>
using namespace std;
#define MAXSIZE 20
typedef struct node
{
struct node *lchild;
struct node *rchild;
int data;
int count;
}node,*Bitree;
void init_tree(Bitree &t)
{
t=NULL;
}
//二叉树的建立
void insert(Bitree &t, const int &data)
{
if(!t)
{
t=(node *)malloc(sizeof(node));
t->data=data;
t->count=1;
t->lchild=NULL;
t->rchild=NULL;
}
else
{
if(t->data==data)
{ t->count++;return;}
if(data<t->data)
{
if(!t->lchild)
{
t->lchild=(node* )malloc(sizeof(node));
t->data=data;
t->count=1;
t->lchild=NULL;
t->rchild=NULL;
}
else insert(t->lchild,data);
}
else
{
if(!t->rchild)
{
t->rchild=(node*)malloc(sizeof(node));
t->data=data;
t->count=1;
t->lchild=NULL;
t->rchild=NULL;
}
else insert(t->rchild,data);
}
}
}
//求二叉树的第一条最长路径长度,并输出此路径上各结点的值
void LongestPath(Bitree &T,int (&longestpath)[MAXSIZE],int (¤tpath)[MAXSIZE],int& longest,int current)
{
if(!T)
{
if(current>longest)
for(int i=1;i<=current;++i)
{
longestpath[i]=currentpath[i];
longest=current;
}
}
else
{
currentpath[++current]=T->data;
if(T->lchild)
LongestPath(T->lchild,longestpath,currentpath,longest,current);
LongestPath(T->rchild,longestpath,currentpath,longest,current);
current--;
}
}
int main()
{
int longestpath[MAXSIZE];
int currentpath[MAXSIZE];
int longest=0;
static Bitree T;
init_tree(T);
insert(T,10);
insert(T,5);
insert(T,3);
insert(T,4);
insert(T,2);
insert(T,1);
insert(T,7);
insert(T,6);
insert(T,8);
insert(T,9);
insert(T,11);
insert(T,12);//只能输出此结点,之前插入的都白费了
LongestPath(T,longestpath,currentpath,longest,0);
for(int i=1;i<=longest;++i)
cout<<longestpath[i]<<' ';
return 0;
}