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);
    }
};
相关推荐
ShineWinsu5 分钟前
对于数据结构:堆的超详细保姆级解析——下(堆排序以及TOP-K问题)
c语言·数据结构·c++·算法·面试·二叉树·
DuHz27 分钟前
基于时频域霍夫变换的汽车雷达互干扰抑制——论文阅读
论文阅读·算法·汽车·毫米波雷达
hetao17338371 小时前
ZYZ28-NOIP模拟赛-Round4 hetao1733837的record
c++·算法
Nebula_g1 小时前
C语言应用实例:解方程(二分查找)
c语言·开发语言·学习·算法·二分查找·基础
少许极端2 小时前
算法奇妙屋(十)-队列+宽搜(BFS)
java·数据结构·算法·bfs·宽度优先·队列
异步的告白3 小时前
C语言-数据结构-1-动态数组
c语言·数据结构·c++
想唱rap4 小时前
Linux开发工具(4)
linux·运维·服务器·开发语言·算法
前端炒粉4 小时前
21.搜索二维矩阵 II
前端·javascript·算法·矩阵
星释4 小时前
Rust 练习册 :Rail Fence Cipher与栅栏密码
开发语言·算法·rust