/* * 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; }