zoukankan      html  css  js  c++  java
  • 二叉树中的常见算法题

    1、二叉树的每个根节点到叶节点的路径代表一个数字,求所有根节点到叶节点所组成数字的和。

      sum=12+13=25

     1 int addsumnumber(BinTree *root,int sum)
     2 {
     3     if(root == NULL)
     4         return 0;
     5     if (root->left == 0 && root->right == 0)    
     6         return sum *10 + root->data;  //左右子树都为空,则返回当前值
     7     //递归遍历,将左右子树的值相加
     8     return addsumnumber(root->left,sum *10 + root->data) + addsumnumber(root->right,sum *10 + root->data);
     9 }
    10 int sumnumbers(BinTree *root)
    11 {
    12     if(root == NULL)
    13         return 0;
    14     int sum = 0;
    15     sum = addsumnumber(root,sum);
    16     return sum;
    17 }

    2、计算二叉树的最大深度

    1 int bintreemaxdepth(BinTree *root)
    2 {
    3     if(root == NULL)
    4         return 0;
    5     int ldepth = bintreemaxdepth(root->left);
    6     int rdepth = bintreemaxdepth(root->right);
    7     return max(ldepth,rdepth)+1;
    8 }

    3、计算二叉树的最小深度

     1 int solution::MinDepth(TreeNode *root)
     2 {
     3     if (root ==NULL)
     4         return 0;
     5     int leftdepth = MinDepth(root->left);
     6     int rightdepth = MinDepth(root->right);
     7     if (leftdepth==0 && rightdepth==0)
     8         return 1;
     9     if (leftdepth==0)
    10         leftdepth = INT_MAX;
    11     if (rightdepth==0)
    12         rightdepth = INT_MAX;    
    13     return min(leftdepth,rightdepth)+1;
    14 }

     4、二叉树中叶子节点个数

    1 int bintreeleafnum(BinTree *root)
    2 {
    3     if(root == NULL)
    4         return 0;
    5     if(root->left == NULL && root->right == NULL)
    6         return 1;
    7     //总的叶子树=左子树的叶子树+右子树的叶子树
    8     return bintreeleafnum(root->left) + bintreeleafnum(root->right);
    9 }
  • 相关阅读:
    Angularjs html文本显示
    .net与.net core学习目录
    数据库学习目录
    WCF学习目录
    sql学习目录
    EF学习目录
    git for Windows
    图谱论(Spectral Graph Theory)基础
    2017机器学习相关会议时间
    数值分析教材统计
  • 原文地址:https://www.cnblogs.com/tracyhan/p/5444401.html
Copyright © 2011-2022 走看看