寻找叶子到根的路径
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define OK 1
#define TRUE 1
#define FALSE 0
#define ERROR 0
typedef struct Node{ //二叉树的链式存储结点
char data;
int status;
struct Node *Lchild;
struct Node *Rchild;
}BiTNode,*BiTree;
void CreateBiTree(BiTree *root){ //形参采用二级指针,实参为结点孩子域地址
char ch;
ch=getchar();
if(ch=='#') *root=NULL;
else{
*root=(BiTree)malloc(sizeof(BiTree));
(*root)->data=ch;
CreateBiTree(&((*root)->Lchild));
CreateBiTree(&((*root)->Rchild));
}
}
void Visit(char data){
printf("%c",data);
}
/********队列函数*******/
typedef struct array{ //定义队列结构
char elem;
struct array *next;
}*PLArray;
typedef struct Node_D{
PLArray front; //指向队头
PLArray rear; //指向队尾
int len; //队列实际长度
}*pNode;
pNode InitArray(pNode S){ //构造空队列
PLArray q=(PLArray)malloc(sizeof(PLArray)); //申请新结点
S=(pNode)malloc(sizeof(pNode));
S->front=q;
S->rear=q;
S->front->next=NULL;
S->len=0;
return S;
}
pNode Push(pNode S,char e){ //插入数据e为队列的队尾
PLArray p=(PLArray)malloc(sizeof(PLArray)); //申请新结点
p->elem=e;
p->next=NULL;
S->rear->next=p; //将结点插入到队尾
S->rear=p; //修改队尾指针
S->len++;
return S;
}
pNode Pop(pNode S,char x){ //删除队头元素,
char e;
if(S->front==S->rear) ;
PLArray p=S->front->next; //p指向队头
e=p->elem;
S->front->next=p->next; //修改头结点的指针域
if(S->rear==p) S->rear=S->front; //最后元素被删除
S->len--;
if(e!=x) Visit(e);
return S ;
}
int ArrayEmpty(pNode S){ //判断队列是否为空
if(S->len==0) return TRUE;
else return FALSE;
}
pNode Pop2(pNode S){ //删除队尾
PLArray q=(PLArray)malloc(sizeof(PLArray)); //申请新结点
PLArray p=S->front->next;
q=S->rear;
while(!(p->next==S->rear)) p=p->next;
S->rear=p;
free(q);
S->len--;
return S;
}
BiTree parent(BiTree T,BiTree root,pNode S){ //T为当前结点,root为根
BiTree p,q;
if(root==NULL) return NULL;
S=Push(S,root->data);
if(root->Lchild==T||root->Rchild==T)
return root;
p=parent(T,root->Lchild,S);
if(p!=NULL)
return p;
else {
q=parent(T,root->Rchild,S);
if(q==NULL) S=Pop2(S);
return q;
}
}
void fun1(BiTree T,BiTree root){
pNode S;
S=InitArray(S);
printf("%c:",T->data);
parent(T,root,S);
while(!ArrayEmpty(S))
S=Pop(S,T->data);
printf("\n");
}
void InOrderLeaf(BiTree T,BiTree root){ //中遍历寻找叶子结点
if(T){
InOrderLeaf(T->Lchild,root);
if(T->Lchild==NULL&&T->Rchild==NULL){
fun1(T,root);
}
InOrderLeaf(T->Rchild,root);
}
}
int main(){
BiTree T;
CreateBiTree(&T);
InOrderLeaf(T,T);
return 0;
}