/* Function: (1) all leaf nodes of the output binary tree (2) Output all paths from the leaf node to the root node (3) The longest path in the output (2) Author: pussy Date: 2015-11-28 */# include<stdio.h> #
include<malloc.h> typedef struct binode{char data;
struct Binode *lchild,*rchild;
}binode,*bitree;
void Longestpath (Bitree t,char path[],int &pathlength,char longestpath[],int &longestlength);
void Createbitree (Bitree &t);
void Allpath (Bitree t,char path[],int &pathlength);
void Disdeaf (Bitree T);
int main () {Bitree t=null;
printf ("Create two Fork Tree:");
Createbitree (T);
Char path[100],longestpath[100];
int pathlength=0,longestlength=0;
printf ("The tree has the following leaf nodes:");
Disdeaf (T);
printf ("\ n");
Allpath (t,path,pathlength);
Longestpath (t,path,pathlength,longestpath,longestlength);
printf ("The Longest path is:");
for (int i=longestlength;i>=0;i--) {printf ("%c", Longestpath[i]);
} printf ("\ n");
return 0;
}//Create two fork tree void Createbitree (Bitree &t) {char ch=getchar (); The input character ' # ' represents an empty if (ch== ' # ') t=null;
else {t= (bitree) malloc (sizeof (Binode));
t->data=ch;
t->lchild=t->rchild=null;
Createbitree (T->lchild);
Createbitree (T->rchild); }///Output all leaf nodes to the root path//when t is a null node, return to the previous layer, do not process//when t is a leaf node, first add t to the path, in the output path//when T is not a leaf node and is not a null node, the node is added to the path in//path from the root node , Pathlength is the length of path, void Allpath (Bitree t,char path[],int &pathlength) {if (t!=null) {if (t->lchild
==null&&t->rchild==null) {path[pathlength]=t->data;
printf ("%c leaf node to root node path is:", t->data);
for (int i=pathlength;i>=0;i--) printf ("%c", Path[i]);
printf ("\ n");
} else {path[pathlength++]=t->data;
Allpath (t->lchild,path,pathlength);
Allpath (t->rchild,path,pathlength);
pathlength--; }}}//Output The longest path, the algorithm and output all paths similar//different, when encountering the leaf node, compare the current path and whether the longest path//is longer than the current record, if yes, update the mostLong path.
void Longestpath (Bitree t,char path[],int &pathlength,char longestpath[],int &longestlength) {if (T!=NULL)
{if (t->lchild==null&&t->rchild==null) {path[pathlength]=t->data;
if (pathlength>longestlength) {for (int i=pathlength;i>=0;i--) {
Longestpath[i]=path[i];
} longestlength=pathlength;
}} else {path[pathlength++]=t->data;
Longestpath (t->lchild,path,pathlength,longestpath,longestlength);
Longestpath (t->rchild,path,pathlength,longestpath,longestlength);
pathlength--;
}}} void Disdeaf (Bitree T) {if (t!=null) {if (t->lchild==null&&t->rchild==null)
printf ("%c", t->data);
Disdeaf (T->lchild);
Disdeaf (T->rchild); }
}