数据结构16——计算二叉树叶子结点数目(耿6.14)

Description

二叉树按照二叉链表方式存储,编写程序,计算二叉树中叶子结点的数目。

Input

按先序输入二叉树各结点,其中#表示取消建立子树结点。

Output

输出二叉树中叶子节点的数目。

  • Sample Input 
    ABD##EH###CF#I##G##
  • Sample Output
    4

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

typedef struct BTNode{
	char data;
	struct BTNode *lchild;
	struct BTNode *rchild;
}BTNode;

BTNode *CreateTree(){
	char s;
	BTNode *root = (BTNode*)malloc(sizeof(BTNode));
	s = getchar();
	if(s == '#')
	    return NULL;
	else{
		root->data = s;
		root->lchild = CreateTree();
		root->rchild = CreateTree();
	}
	return root;
}

int CntTree(BTNode *root){
	if(!root)
	    return 0;
	else{
		if((!root->lchild) && (!root->rchild))
		    return 1;
		else{
			return(CntTree(root->lchild)+CntTree(root->rchild));
		}
	}
}

int main(){
	BTNode *root;
	root = CreateTree();
	int cnt;
	cnt = CntTree(root);
	printf("%d\n", cnt);
	return 0;
}
题解:构建二叉树,遍历寻找叶子节点。

猜你喜欢

转载自blog.csdn.net/chengchencheng/article/details/80627883