统计二叉树每层节点个数并打印每层节点

先看百度一道面试题:

有一颗二叉树,定义树的高度为从根到叶子节点的最长距离,树的宽度为每层节点的最大值,树的面积定义为高度和宽度的乘积。写一个函数计算一个二叉树的面积。(15)

解决这道题参考资料剑指offer和编程之美,分别求求二叉树高度和宽度。


都是采用递归:

求高度参考:http://blog.csdn.net/buyingfei8888/article/details/38345591

求每层节点个数需要先求出高度

代码:

#include <iostream>
using namespace std;

typedef struct node{
	int data;
	struct node *lchild;
	struct node *rchild;
}Node ,*pNode;

void createTree(pNode & root){
	int temp;
	scanf("%d",&temp);
	if(0 != temp){
		root=(pNode) malloc (sizeof(Node));
		root->data = temp;
		createTree(root->lchild);
		createTree(root->rchild);
	}else{
		root=NULL;
	}
	
}

void printAll(const pNode root){
    pNode p = root;
	if(p){
		cout<< p->data<< " ";
		printAll(p->lchild);
		printAll(p->rchild);
	}
	
}
//打印一层节点
int printNodeAtLevel(pNode root,int level,int &count){
	if(!root || level <0)
		return 0;
	if(0 == level){
		cout<< root->data<< " ";
		count++;
		return 1;
	}
	return printNodeAtLevel(root->lchild,level-1,count) + printNodeAtLevel(root->rchild,level-1,count);
}




//类似后序遍历,效率比较高,不会重复访问节点
void  btDepth(const pNode  root,int &depth){
	if(NULL == root){
		depth=0;
		return ;
	}
	int left ;
	btDepth(root->lchild,left);
	
    int right ;
	btDepth(root->rchild,right);
	depth = left > right ? left +1 : right +1;
}
int main(){
	pNode root=NULL;
	createTree(root);
	cout<<endl;
	printAll(root);
	cout<<endl;
	int depth=0;
	btDepth(root,depth);
	cout<<endl<<depth;
	cout<<endl;

	//循环遍历 ,打印各层几点
	for(int i=0;i<depth;i++){
		int count=0;
		printNodeAtLevel(root,i,count);
		cout << " 节点个数为:"<< count<<endl;
	}
	return 0;

}

运行结果:



  • 4
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值