zoukankan      html  css  js  c++  java
  • Maximum Depth of Binary Tree

    Given a binary tree, find its maximum depth.

    The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.


    先贴一个我超时的代码:

    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        int maxDepth(TreeNode *root) {
            int depth = 0;
            TreeNode *p = root;
            if(!p) return depth;
            if(maxDepth(p->left)>maxDepth(p->right))
                return depth + maxDepth(p->left);
            else
                return depth + maxDepth(p->right);
            
        }
    };

    超时原因:

    ~很显然, maxDepth(p->left)每次求的时候都计算了两次, 这个真是太不明智了

    提醒以后,尽量用变量代替繁琐的实现

    ~超时后不是考虑用非递归方法, 这个当然也可以, 而是考虑递归方法是否是最优的


    正确代码:

    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        int maxDepth(TreeNode *root) {
            if(!root) return 0;
            int leftdepth = maxDepth(root->left);
            int rightdepth= maxDepth(root->right);
            if(leftdepth>rightdepth)
                return 1 + leftdepth;
            return 1 + rightdepth;
            
        }
    };


    每天早上叫醒你的不是闹钟,而是心中的梦~
  • 相关阅读:
    objective-C nil,Nil,NULL 和NSNull的小结
    Calendar控件点击下个月按钮后,本月标记的各个具体天的样式都取消
    如何让Button的Text垂直居中显示
    html基础总结2
    html基础总结1
    html基础总结
    微信空白页获取用户openid
    网址
    网站式更新后台代码
    JavaScriptSerializer引用
  • 原文地址:https://www.cnblogs.com/vintion/p/4116992.html
Copyright © 2011-2022 走看看