链式静态二叉树遍历

#include <stdio.h>
#include <malloc.h> 
//静态创建二叉树
typedef struct TNode{
	char data;
	struct TNode * pLchild;
	struct TNode * pRchild; 
}TNODE,*PTNODE; 

PTNODE CreateTree();//创建二叉树 
void PrePrintTree(PTNODE);//先序遍历
void PrePrintTreeCount(PTNODE,int *);//先序遍历以及叶子节点的个数  
void InPrintTree(PTNODE);//中序遍历
void PostPrintTree(PTNODE);//后续遍历
 
int main(void){
	PTNODE pT = CreateTree();
	printf("先序遍历:"); 
	PrePrintTree(pT); 
	printf("\n"); 
	
	printf("中序遍历:"); 
	InPrintTree(pT); 
	printf("\n"); 
	
	printf("后序遍历:");
	PostPrintTree(pT);
	printf("\n"); 
	
	//先序遍历以及计算叶子节点个数 
	int count = 0;
	printf("先序遍历:");
	PrePrintTreeCount(pT,&count);
	printf("叶子个数:%d\n",count);
 
	return 0; 
} 
//创建二叉树
 PTNODE CreateTree(){
 	 PTNODE pA = (PTNODE)malloc( sizeof(TNODE) );
 	 PTNODE pB = (PTNODE)malloc( sizeof(TNODE) );
  	 PTNODE pC = (PTNODE)malloc( sizeof(TNODE) );
  	 PTNODE pD = (PTNODE)malloc( sizeof(TNODE) );
  	 PTNODE pE = (PTNODE)malloc( sizeof(TNODE) );
	 pA->data = 'A';
	 pB->data = 'B';
	 pC->data = 'C';
	 pD->data = 'D';
	 pE->data = 'E'; 
	 pA->pLchild = pB;
	 pA->pRchild = pC;
	 pB->pLchild = NULL;
	 pB->pRchild = NULL;
	 pC->pLchild = pD;
	 pC->pRchild = NULL;
	 pD->pLchild = NULL;
	 pD->pRchild = pE;
	 pE->pLchild = NULL;
	 pE->pRchild = NULL;
	 return pA; 
 } 
 //先序遍历
 void PrePrintTree(PTNODE pT){
 	 if(pT){
		printf("%c\t",pT->data);
		if(pT->pLchild){
			PrePrintTree(pT->pLchild); 
		} 	
		if(pT->pRchild){
			PrePrintTree(pT->pRchild); 
		} 
	 } 
 } 
 //中序遍历
 void InPrintTree(PTNODE pT){
 	if(pT){
 		if(pT->pLchild){
			InPrintTree(pT->pLchild); 
		} 
		printf("%c\t",pT->data);
		if(pT->pRchild){
			InPrintTree(pT->pRchild); 
		} 	
	} 
 } 
 //后序遍历
 void PostPrintTree(PTNODE pT){
 	if(pT){
		if(pT->pLchild){
			PostPrintTree(pT->pLchild); 
		}
		if(pT->pRchild){
			PostPrintTree(pT->pRchild); 
		}
		printf("%c\t",pT->data); 
	} 
 } 
//先序遍历以及叶子节点的总计
void PrePrintTreeCount(PTNODE pT,int * count){
	if(pT){
		printf("%c\t",pT->data);
		if(!pT->pLchild && !pT->pRchild){//左右子节点都为空的时候 
			(*count)++; 
		} 
		if(pT->pLchild){ 
			PrePrintTreeCount(pT->pLchild,count); 
		}
		if(pT->pRchild){
			PrePrintTreeCount(pT->pRchild,count); 
		} 
	} 
} 


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值