/*
* description: 计算二叉树的层数和节点数
* writeby: nick
* date: 2012-10-23 16:16
*
*/
#include <iostream>
using namespace std;
struct node
{
int item;
node *l, *r;
node(int n)
{item=n; l=0; r=0;}
};
typedef node *link;
//计算节点总数
int count(link h)
{
if(h==0) return 0;
return count(h->l) + count(h->r) + 1;
}
//计算高度
int height(link h)
{
if(h==0) return -1;
int u=height(h->l);
int v=height(h->r);
return u>v?u+1:v+1;
}
int main()
{
link root = new node(4);
root -> l = new node(5);
root -> r = new node(6);
root->l->l = new node(7);
root->l->r = new node(8);
cout << count(root) << " " << height(root);
return 0;
}
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步