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);
    }
};
相关推荐
青山是哪个青山10 分钟前
动态规划DP
算法·动态规划
水水沝淼㵘16 分钟前
嵌入式开发学习日志(数据库II && 网页制作)Day38
服务器·c语言·网络·数据结构·数据库·学习
looklight1 小时前
7. 整数反转
c++·算法·leetcode·职场和发展
Closet1231 小时前
Codeforces 2025/6/11 日志
c++·算法·codeforces
緈福的街口2 小时前
【leetcode】36. 有效的数独
linux·算法·leetcode
心扬4 小时前
python数据结构和算法(5)
数据结构·python·算法
gogoMark5 小时前
FaceFusion 技术深度剖析:核心算法与实现机制揭秘
算法
倔强的石头_5 小时前
【数据结构与算法 经典例题】使用队列实现栈(图文详解)
后端·算法
黑色的山岗在沉睡6 小时前
P1216 [IOI 1994] 数字三角形 Number Triangles
算法·动态规划