zoukankan      html  css  js  c++  java
  • 微软面试题:写程序找出二叉树的深度

    一个树的深度等于max(左子树深度,右子树深度)+1。可以使用递归实现。

    int DepthOfTree(BiTreeNode* root)
    {
     if(NULL == root)
     {
      return 0;
     }
     return max(DepthOfTree(root->leftChild), DepthOfTree(root->rightChild))+1;
    }

    也可以采用下面的思路:

    类似于递归的先序遍历,层层向下计算,每向下计算一层,深度
                     就加1,CalTreeDepth(PNode pn, unsigned n)中的第二个
                     参数表示上一层的深度,所以程序在调用时, 假设proot为整个
                     树的根节点,则其深度depth为:
                                       unsigned depth = CalTreeDepth(proot, 0);
    */
    代码如下:

    unsigned CalTreeDepth(PNode pn, unsigned n)
    {
            static unsigned d = 0;          //使用static变量d来记录出现的最大深度
            if(pn)
            {
                if(n+1 > d)
                    d = n+1;
                CalTreeDepth(pn->left, n+1);
                CalTreeDepth(pn->right, n+1);
            }
            return d;
    }
  • 相关阅读:
    mysql 查询某年某月数据~(如果数据表用时间戳)
    mongo_4.25 find() hasNext() next()
    在YII框架中有2中方法创建对象:
    bootsrap[$data]
    date
    cookie
    JavaScript shell, 可以用到 JS 的特性, forEach
    在 Yii框架中使用session 的笔记:
    mysql查询今天、昨天、7天、近30天、本月、上一月 数据
    Python 自定义异常练习
  • 原文地址:https://www.cnblogs.com/rollenholt/p/2414388.html
Copyright © 2011-2022 走看看