zoukankan      html  css  js  c++  java
  • 树——二叉树结点数目、高度和度数的实现

    1,二叉树中结点的数目的实现:

           1,定义功能:count(node):

                  1,在 node 为根结点的二叉树中统计结点数目;

           2,功能函数代码实现:

    1    /* 定义数结点数目的功能函数 */
    2     int count(BTreeNode<T>* node) const
    3     {
    4         return (node != NULL) ? (count(node->left) + count(node->right) + 1) : 0 ; 
    5    }

      3,成员函数代码实现:

    1 int count() const 

    2 {

    3 return count(root());

    4 }
     

    2,二叉树的高度:

     

           1,定义功能:height(node):

                  1,获取 node 为根结点的二叉树的高度;

      2,功能函数代码实现:

     1     /* 定义以 node 为根结点的二叉树的高度 */
     2     int height(BTreeNode<T>* node) const
     3     {
     4         int ret = 0;
     5 
     6         if( node != NULL )  // 空结点返回 0 ,递归出口
     7         {
     8             int lh = height(node->left);
     9             int rh = height(node->right);
    10             ret = ((lh > rh) ? lh : rh) + 1;
    11         }
    12 
    13         return ret;
    14     }

      3,成员函数代码实现:

    1 int height() const 

    2 {

    3 return height(root());

    4 }
     

    3,树的度数:

     

           1,定义功能:degree(node):

                  1,获取 node 为根结点的二叉树的度数;

           2,功能函数代码实现:

     1    /* 定义以 node 为根结点的二叉树的度数 */
     2     int degree(BTreeNode<T>* node) const
     3     {
     4         int ret = 0;
     5 
     6         if( node != NULL )
     7         {
     8             // 非常精妙的改写,由下往上改写;
     9             BTreeNode<T>* child[] = { node->left, node->right};
    10             ret = (!!node->left + !!node->right);  // 结点数的度
    11 
    12             for(int i=0; (i<2) && (ret<2); i++)  //保证结点度数达到要求后,直接不求
    13             {
    14                 int d = degree(child[i]);
    15 
    16                 if( ret < d )
    17                 {
    18                     ret = d;
    19                 }
    20             } 
    21         }
    22 
    23         return ret;
    24    }

      3,功能函数代码实现:

    1 int degree() const 

    2 {

    3 return degree(root());

    4 }
     
  • 相关阅读:
    HYSBZ 2818 gcd
    hdu1695 GCD
    HYSBZ 2301
    poj 2096
    正则表达式匹配HTML标签或标记
    [转载]Sed 命令详解 正则表达式元字符
    [转载]Shell删除各种注释的脚本
    [转载]sed实现直接修改文件内容
    [转载]强大的grep用法详解:grep与正则表达式
    [转载]【Shell脚本】逐行处理文本文件
  • 原文地址:https://www.cnblogs.com/dishengAndziyu/p/10925512.html
Copyright © 2011-2022 走看看