当前位置: 首页 > news >正文

leetcode104 二叉树的最大深度

使用迭代法的话,使用层序遍历是最为合适的,因为最大的深度就是二叉树的层数,和层序遍历的方式极其吻合。

在二叉树中,一层一层的来遍历二叉树,记录一下遍历的层数就是二叉树的深度。

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

方法 1:标准 DFS 递归(后序遍历)

思路:计算左子树和右子树的深度,取较大值并 +1(当前层深度)。

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

方法 2:DFS + 传当前深度(前序遍历)

思路:在递归时维护当前深度,并更新全局最大深度。

class Solution {
private:
    int max = 0;
    void traverse(TreeNode* cur, int level){
        if(cur == nullptr) return;
        if(level > max) max = level;
        if(cur->left) traverse(cur->left, level+1);
        if(cur->right) traverse(cur->right, level+1);
    }
public:
    int maxDepth(TreeNode* root) {
        traverse(root, 1);
        return root ? max : 0;
    }
};

相关文章:

  • Spring Boot中自定义注解的创建与使用
  • C语言编译和链接错题
  • IDEA/WebStrom操作之commit前批量清除console.log()与debugger
  • Java基础 4.5
  • Fortran 中读取 MATLAB 生成的数据文件
  • 基于SpringBoot的养老院信息管理系统(源码+数据库)
  • Java的Selenium的特殊元素操作与定位之模态框
  • 7-9 趣味游戏
  • Ubuntu-安装redis
  • 【Kubernetes】ConfigMap 和 Secret 的作用是什么?它们如何影响应用配置?
  • d202545
  • 【MediaPlayer】基于libvlc+awtk的媒体播放器
  • April Fools Day Contest 2025 A-F(没有E) 题解
  • 软件工程面试题(二十八)
  • [ 计算机网络 ] | HTTP协议(一)
  • MySQL:查询
  • 获取KUKA机器人诊断文件KRCdiag的方法
  • Mathematics | Branch
  • STM32 的编程方式总结
  • CCF GESP Python编程 三级认证真题 2025年3月