数据结构:

以二叉链表作为二叉树的存储结构,统计二叉树的叶结点个数。首先建树,递归走起。

 

#include<iostream>
using namespace std;

int ans;	//叶子节点数 

typedef struct biTnode{
	
	char data;	
	struct biTnode *lc,*rc;
}biTnode,*bitree;

void cr_bitree(bitree &T)
{//先序建树 
		char ch;
		cin>>ch;
		if(ch=='#')	 T = NULL;//空树 
		else{
			T= new biTnode;//ch!='#',建节点 
			T->data = ch;
			cr_bitree(T->lc);// 左子树 
			cr_bitree(T->rc);// 右子树 
		}	
}

void find(bitree T)
{
	if(T==NULL)	return;//节点为空不计入 
	if(T->lc==NULL&&T->rc==NULL) 
		ans++;//当且仅当左右孩子为空,节点date不为空时,ans++; 
	else
	{
		find(T->lc);//找左树(左孩子) 
		find(T->rc);//找右树(右孩子) 
	}
}

int main()
{
		ans=0;
		bitree T;
		cr_bitree(T);
		find(T);
		cout<<ans<<endl;
		delete T;
		return 0;
}

 

 

输出的结果:

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐