您的位置:首页 > 其它

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

2014-08-02 10:36 253 查看
先看百度一道面试题:

有一颗二叉树,定义树的高度为从根到叶子节点的最长距离,树的宽度为每层节点的最大值,树的面积定义为高度和宽度的乘积。写一个函数计算一个二叉树的面积。(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;

}

运行结果:



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息