首页 > 其他 > 详细

LC104 二叉树的最大深度

时间:2020-07-16 13:22:43      阅读:43      评论:0      收藏:0      [点我收藏+]

本题给定的函数参数只有结点指针,由于无法传入当前节点的深度,无法使用自顶向下的方法求解

递归解法-自底向上

class Solution {
public:
    int maxDepth(TreeNode* root) {
        if(root == nullptr)
            return 0;
        int leftDep = maxDepth(root->left) + 1;
        int rightDep = maxDepth(root->right) + 1;
        return leftDep > rightDep ? leftDep : rightDep;
    }
};

如果参数可以多一个int类型,则可以使用自顶向下的方法,直接调用maxDepth(root, 0)即可

递归解法-自顶向下

class Solution {
private:
    int ans;
public:
    int maxDepth(TreeNode* root, int dep) {
        if(!root->left && !root->right)
            return ans > (dep + 1) ? ans : (dep + 1);
        maxDepth(root->left, dep + 1);
        maxDepth(root->right, dep + 1);
    }
};

非递归解法

也可以使用层次遍历来解决这个问题,参考之前层次遍历的写法即可

class Solution {
public:
    int maxDepth(TreeNode* root) {
        int res = 0;
        if(root == nullptr)
            return res;
        queue<TreeNode*> level;
        level.push(root);
        while(!level.empty()){
            int size = level.size();
            for(int i = 0; i < size; i ++){
                TreeNode* nowNode = level.front();
                if(nowNode->left != nullptr) 
                    level.push(nowNode->left);
                if(nowNode->right != nullptr) 
                    level.push(nowNode->right);
                level.pop();
            }
            res++;
        }
        return res;
    }
};

LC104 二叉树的最大深度

原文:https://www.cnblogs.com/imagineincredible/p/13321671.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!