zoukankan      html  css  js  c++  java
  • 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;
    }
  • 相关阅读:
    loadOnStartup = 1
    TP复习8
    TP复习7
    TP复习6
    TP复习5
    TP复习4
    TP复习3
    TP复习2
    TP复习
    document.createElement("A");
  • 原文地址:https://www.cnblogs.com/wouldguan/p/2735707.html
Copyright © 2011-2022 走看看