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;
            
        }
    };


    每天早上叫醒你的不是闹钟,而是心中的梦~
  • 相关阅读:
    Java 对象初始化
    Java 栈和堆
    值得细品
    磁盘的分区、格式化与挂载
    VirtualBox预存空间不足
    做个备忘
    SQL查数据库有哪些触发器,存储过程...
    SQL 中 CASE
    FMX的Style中的Effects的注意问题
    Python图像处理库(2)
  • 原文地址:https://www.cnblogs.com/vintion/p/4116992.html
Copyright © 2011-2022 走看看