数据结构——二叉树上某层次的叶子结点个数

二叉树上某层次的叶子结点个数

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

typedef struct Node{        //二叉树的链式存储结点 
	char data;
	int depth; 
	struct Node *Lchild;
	struct Node *Rchild;
}BiTNode,*BiTree;

int leaf = 0;

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(BiTree T,int k){
	if(T->depth==k){
		if(T->Lchild==NULL&&T->Rchild==NULL)  leaf++;
	}
}

int h=1;        //当前T结点所在层次 
int depth=0;   //记录当前最大层次 
void TreeDepth(BiTree T,int h){
	if(T){
		T->depth=h;    //记录当前结点的层次 
		if(h>depth)  depth=h;
		TreeDepth(T->Lchild,h+1);
		TreeDepth(T->Rchild,h+1);
	}
}

void PreOrder(BiTree T,int k){      //先序递归遍历
     if(T){
     	Visit(T,k);
     	PreOrder(T->Lchild,k);
     	PreOrder(T->Rchild,k);
	 } 	
}

int main(){
	BiTree T;
	int k=3;
	CreateBiTree(&T);
	TreeDepth(T,h);
	
	scanf("%d",&k);
	PreOrder(T,k);
	printf("%d",leaf);
	return 0;
} 

猜你喜欢

转载自blog.csdn.net/qq_41596568/article/details/84328035
今日推荐