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);
    }
};
相关推荐
云里雾里!5 小时前
力扣 209. 长度最小的子数组:滑动窗口解法完整解析
数据结构·算法·leetcode
CoderYanger6 小时前
递归、搜索与回溯-穷举vs暴搜vs深搜vs回溯vs剪枝:12.全排列
java·算法·leetcode·机器学习·深度优先·剪枝·1024程序员节
憨憨崽&7 小时前
进击大厂:程序员必须修炼的算法“内功”与思维体系
开发语言·数据结构·算法·链表·贪心算法·线性回归·动态规划
chem41117 小时前
C 语言 函数指针和函数指针数组
c语言·数据结构·算法
liu****8 小时前
八.函数递归
c语言·开发语言·数据结构·c++·算法
客梦8 小时前
数据结构-树结构
数据结构·笔记
CM莫问8 小时前
详解机器学习经典模型(原理及应用)——岭回归
人工智能·python·算法·机器学习·回归
DuHz8 小时前
论文阅读——Edge Impulse:面向微型机器学习的MLOps平台
论文阅读·人工智能·物联网·算法·机器学习·edge·边缘计算
梦想的旅途28 小时前
基于雪花算法(Snowflake)的 Go 语言唯一 ID 生成与并发安全实现
算法·安全·golang
Vanranrr9 小时前
C++临时对象与悬空指针:一个导致资源加载失败的隐藏陷阱
服务器·c++·算法