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);
    }
};
相关推荐
洛水水9 小时前
【力扣100题】58.轮转数组
算法·leetcode
资深流水灯工程师9 小时前
LMS 最小均方算法在 DSP 上的 C 语言实现
算法
风筝在晴天搁浅9 小时前
阿里 LeetCode 876.链表的中间节点
算法·leetcode·链表
玖釉-9 小时前
二叉树展开为链表:从先序遍历到原地指针重排
c++·windows·算法·leetcode·链表
05候补工程师9 小时前
【408考研·数据结构专题】二叉树、树与森林、线索树及哈夫曼树核心考点与秒杀技巧深度总结
数据结构·经验分享·笔记·考研·算法
吃好睡好便好9 小时前
矩阵的加减运算
开发语言·人工智能·学习·线性代数·算法·matlab·矩阵
吃好睡好便好9 小时前
提取矩阵特定多行元素
开发语言·线性代数·算法·matlab·矩阵
葫三生9 小时前
多模态视角下的一部当代东方创世史诗 ——《论三生原理》?(扩版)
人工智能·科技·算法·机器学习·开源
stsdddd10 小时前
【YOLO算法包裹背包行李箱塑料袋包装纸盒快递盒带目标检测数据集】
算法·yolo·目标检测
洛水水10 小时前
【力扣100题】52.最小路径和
算法·leetcode