二叉树求深度和宽度,叶子节点数,总结点数

#include<iostream>
//#include<malloc.h> //c malloc和free,C++ new和delete 
#include<queue>
using namespace std;

//二叉链表方式,最常用 
#define MAXSIZE 100 
typedef char ElementType;
struct BTNode{
	ElementType data;
	BTNode *lchild;
	BTNode *rchild;
};

//先序创建二叉树 
BTNode * CreateTree(){
	BTNode * T=new BTNode;//(BTNode *)malloc(sizeof(BTNode))
	
	char ch;cin>>ch;//输入 
	if(ch=='#'){
		return NULL;
	}else{
		T->data=ch;
		T->lchild=CreateTree();
		T->rchild=CreateTree();		
	} 

	return T;	
}

//利用后序遍历求二叉树的深度,节点个数
int PostTree(BTNode * T){
	if(!T) return 0;
	
	int left,right,depth,nodenum;	
	left=PostTree(T->lchild);
	right=PostTree(T->rchild);
	
	depth=( left>right?left:right )+1; //深度=max(left,right)+1 
	nodenum=left+right+1;//节点个数=left+right+1 

	return depth; //return nodenum;求节点数  
} 

//求叶子节点个数 
int Leaf(BTNode * T){
	if(!T) return 0;
	
	if( !(T->lchild) && !(T->rchild) ){
		return 1;
	}else 
		return ( Leaf(T->lchild)+Leaf(T->rchild) );	
}

//求二叉树的宽度(同一层上的最大节点数),利用队列
int MaxNode(BTNode * T){
	if(!T) return 0; 
	
	int frontLevelWidth,curLevelWidth,maxLevelWidth;//上层的节点总数,本层的节点总数 ,节点数最大值 
	
	queue<BTNode *> que; 
	BTNode * p;
	que.push(T);//根节点入队
	frontLevelWidth=1; maxLevelWidth=1;//最少有一个根节点
	
	while(!que.empty()){//保证队列不空 
		while(frontLevelWidth){
			p=que.front();
			que.pop();
			if(p->lchild) que.push(p->lchild);
			if(p->rchild) que.push(p->rchild);
			frontLevelWidth--;
		} 
		curLevelWidth=que.size();
		if(curLevelWidth>maxLevelWidth)  maxLevelWidth=curLevelWidth;
		frontLevelWidth=curLevelWidth;
	} 
	
	return maxLevelWidth;
} 


int main(){
	//freopen("input.txt","r",stdin);//ABD###CE##F##
	BTNode * T;
	T=CreateTree();
	
	cout<<PostTree(T)<<endl;
	cout<<MaxNode(T)<<endl;

	
    return 0;
}

关于先序建树


  • 8
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值