數據結構:葉子節點的個數

#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#define MAXLEN 100
#define NLAYER  4

typedef struct BiTNode               
{
	char data;                       
    struct BiTNode *LChild,*RChild;  
}BiTNode,*BiTree;
BiTree T;


void CreateBiTree(BiTree *bt)
{ 
	char ch;
    scanf("%c",&ch);  
    if(ch=='0') *bt=NULL;
    else 
	{
		*bt=(BiTree)malloc(sizeof(BiTNode)); 
        (*bt)->data=ch;
        CreateBiTree(&((*bt)->LChild));      
        CreateBiTree(&((*bt)->RChild));      
	}
}

void  PreOrderLeaf(BiTree root) 
{
	if (root!=NULL)
	{
		if (root ->LChild==NULL && root ->RChild==NULL)
			printf("%c  ",root ->data); 
		PreOrderLeaf(root ->LChild);      
		PreOrderLeaf(root ->RChild);      
	}
	
}


int LeafCount(BiTree root)
{
	int LeafNum;
	if(root==NULL)	
		LeafNum=0;
	else 
		if((root->LChild==NULL)&&(root->RChild==NULL))
			LeafNum=1;
		else 
			LeafNum=LeafCount(root->LChild)+LeafCount(root->RChild);
 
	return LeafNum;
}

int main()
{
	    
	    printf("首先請輸入二叉樹的結點序列:\n");
		CreateBiTree(&T);
		printf("葉子結點爲:");
		 PreOrderLeaf(T); 
		 printf("\n");
		printf("葉子結點個數爲:%d",LeafCount(T));
	    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章