数据结构——寻找叶子结点到根节点的路径

寻找叶子到根的路径

#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;
} 
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值