创建一个二叉树,然后找到二叉树中最长的路径,并输出。
代码如下
#include<stdio.h>
#include<bits/stdc++.h>
#define MAX 200
typedef char TElemType;
typedef int status;
typedef struct BiNode
{
TElemType data;
struct BiNode *lchild;
struct BiNode *rchild;
}BiNode,*BiTree;
void CreateBiTree(BiTree &T)//二叉树的先序创建
{
TElemType ch;
scanf("%c",&ch);
if(ch=='#')
T=NULL;
else
{
T=(BiNode*)malloc(sizeof(BiNode));
if(!T)
exit(-1);
T->data=ch;
CreateBiTree(T->lchild);
CreateBiTree(T->rchild);
}
}
void longest_path(BiTree T,char *path,int &len,char *longestpath,int &longest_len)
{
if(T!=NULL)
{
path[len++]=T->data;
if(T->lchild==NULL&&T->rchild==NULL)//当遇到叶子结点时,该条路径完毕
{
if(len-1>longest_len)//如果长于longest_len就替换
{
for(int j=0;j<=len-1;j++)
{
longestpath[j]=path[j];
}
longest_len=len-1;//longest_len更新
}
}
longest_path(T->lchild ,path,len,longestpath,longest_len);
longest_path(T->rchild ,path,len,longestpath,longest_len);
len--;
}
}
int main()
{
BiTree T;
printf("创建树输入树T的先序序列(其中使用#代表空节点)\n");
CreateBiTree(T);
char path[MAX]={0};
char longestpath[MAX]={0};
int len=0;
int longest_len=0;
longest_path(T,path,len,longestpath,longest_len);
printf("第一条最长的路径长度为:%d\n",longest_len);
printf("路径为:");
for(int i=0;i<=longest_len;i++)
{
printf("%c ",longestpath[i]);
}
}