C++计算二叉树的节点数和高度


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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM