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);
    }
};
相关推荐
洋不写bug几秒前
链表面试笔试经典题目详细解析,题目多解法,复杂度分析
数据结构·链表·面试
s_w.h1 小时前
【 刷题 】双指针
算法
啥都想学点的研究生1 小时前
一篇文章讲清楚:K-Means聚类算法
算法·kmeans·聚类
白狐_7981 小时前
408 数据结构|KMP做题方法:next、nextval和高频易错点
数据结构·算法
月华路1 小时前
《模型不玄学》第20章 两种评估视角
人工智能·算法·机器学习
禹凕2 小时前
快速幂算法详解与实战
python·算法
xxwl5852 小时前
高斯消元法异或版
人工智能·算法·机器学习
sylviiiiiia2 小时前
leetcode hot 100
python·算法·leetcode
OPEN-F2 小时前
ROS2系列教程:Gazebo插件(关节控制/IMU/激光雷达)
c++·python·数码相机·算法·机器人
luj_17682 小时前
虚实交融中的真实人物塑造
c语言·开发语言·网络·经验分享·算法