zoukankan      html  css  js  c++  java
  • OJ练习24——T104 Maximum Depth of Binary Tree

    求二叉树深度。

    【思路】

    很简单,二叉树经典。

    用递归求左树右树的深度,较大值加1即可。

    【other code】

    int maxDepth(TreeNode *root) {
            if(root==NULL)
                return 0;
            //if(maxDepth(root->left)>=maxDepth(root->right))
                //return maxDepth(root->left)+1;
            //else
                //return maxDepth(root->right)+1;
            int max1=maxDepth(root->left);
            int max2=maxDepth(root->right);
            return max1>max2?max1+1:max2+1;
            //return max(maxDepth(root->left), maxDepth(root->right))+1;
            //return maxDepth(root->left)>maxDepth(root->right)?maxDepth(root->left)+1:maxDepth(root->right)+1;
        }

    【问题】

    注释的是我原来的写法,发现要么用int max1 max2分别表示后,再用条件选择return

    要么直接用max判断递归调用的最大值,否则就会报“超时”错,一长串。

    哦!!!我晓得了!!!

    直接用条件选择如:return maxDepth(root->left)>maxDepth(root->right)?maxDepth(root->left)+1:maxDepth(root->right)+1;

    其实在判断maxDepth(root->left)>maxDepth(root->right)和后面计算maxDepth(root->left)+1是进行了两次递归!!当然是没有返回的!

    原来如此,代码果真不诳我!

  • 相关阅读:
    openwrt 更改 debug 等级(hostapd)
    openwrt 中procd
    openwrt增加串口登录需要密码
    openwrt设置语言的过程
    小程序感悟123
    如何用php实现分页效果
    如何利用h5将视频设置为背景
    关于js中定时器的返回值问题
    canvas二:绘制圆和其他曲线
    canvas一:基本认识
  • 原文地址:https://www.cnblogs.com/ketchups-notes/p/4448843.html
Copyright © 2011-2022 走看看