LeetCode104:二叉树的最大深度

题目描述

给定一个二叉树 root ,返回其最大深度。

二叉树的 最大深度 是指从根节点到最远叶子节点的最长路径上的节点数。

解题思想

可以使用层序遍历

cpp 复制代码
class Solution {
public:
    int maxDepth(TreeNode* root) {
        if (root == nullptr) return 0;

        queue<TreeNode*> que;
        int depth = 0;
        que.push(root);
        while (!que.empty()) {
            vector<int> vec;
            for (int i = que.size(); i > 0; i--) {
                TreeNode* tmp = que.front();
                que.pop();
                vec.push_back(tmp->val);

                if(tmp->left)  que.push(tmp->left);
                if(tmp->right) que.push(tmp->right);
            }
            
            ++depth;
        }
        return depth;
    }
};

解题思想

使用递归:后序遍历,求高度 。 高度==深度

cpp 复制代码
class Solution  {
public:
    int getDepth(TreeNode* node) {
        if (node == nullptr) return 0;
        //左
        int leftH = getDepth(node->left);
        //右
        int rightH = getDepth(node->right);
        //中
        int height = 1 + max(leftH, rightH);
        return height;
    }

    int maxDepth(TreeNode* root) {
        return getDepth(root);
    }
};

精简版

cpp 复制代码
class Solution {
public:
    int getDepth(TreeNode* node) {
        if (node == nullptr) return 0;
      
        return 1 + max(getDepth(node->left), getDepth(node->right));
    }

    int maxDepth(TreeNode* root) {
        return getDepth(root);
    }
};
相关推荐
ULTRA??12 小时前
插入排序算法实现(二分查找搜索版本)
c++·算法
Elias不吃糖12 小时前
LeetCode 71:简化 Unix 路径(Simplify Path)——栈 / vector
算法·leetcode·
sheeta199812 小时前
LeetCode 每日一题笔记 日期:2025.12.15 题目:2110.股票平滑下跌阶段的数目
笔记·算法·leetcode
智者知已应修善业19 小时前
【求中位数】2024-1-23
c语言·c++·经验分享·笔记·算法
地平线开发者19 小时前
PTQ 量化数值范围与优化
算法·自动驾驶
sali-tec19 小时前
C# 基于halcon的视觉工作流-章68 深度学习-对象检测
开发语言·算法·计算机视觉·重构·c#
测试人社区-小明19 小时前
智能弹性伸缩算法在测试环境中的实践与验证
人工智能·测试工具·算法·机器学习·金融·机器人·量子计算
罗西的思考20 小时前
【Agent】MemOS 源码笔记---(5)---记忆分类
人工智能·深度学习·算法
qq_433554541 天前
C++数位DP
c++·算法·图论
AshinGau1 天前
Softmax 与 交叉熵损失
神经网络·算法