【LeetCode热题100】104. 二叉树的最大深度(二叉树)

一.题目要求

给定一个二叉树 root ,返回其最大深度。

二叉树的 最大深度 是指从根节点到最远叶子节点的最长路径上的节点数。

二.题目难度

简单

三.输入样例

示例 1:

输入:root = [3,9,20,null,null,15,7]

输出:3

示例 2:

输入:root = [1,null,2]

输出:2

提示:

树中节点的数量在 [ 0 , 1 0 4 ] [0, 10^4] [0,104]区间内。

-100 <= Node.val <= 100

四.解题思路

解法1:DFS后序遍历求深度

解法2:BFS层序遍历,从root开始将每层结点的左右孩子加入,处理完一层depth++,直到队列空。

五.代码实现

DFS

cpp 复制代码
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int maxDepth(TreeNode* root) {
        if(!root) return 0;
        //后序遍历
        //左子树
        int left = maxDepth(root->left);
        //右子树
        int right = maxDepth(root->right);
        //求深度
        return left > right ? left + 1 : right + 1;
    }
};

BFS

cpp 复制代码
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int maxDepth(TreeNode* root) {
        if(!root) return 0;
        queue<TreeNode*> treeq;
        int depth = 0;
        treeq.push(root);
        while(!treeq.empty())
        {
            int remained = treeq.size();
            while(remained > 0)
            {
                TreeNode* tmp = treeq.front();
                treeq.pop();
                remained--;
                if (tmp->left != nullptr) treeq.push(tmp->left);
                if (tmp->right != nullptr) treeq.push(tmp->right);
            }
            depth++;
        }
        return depth;
    }
};

六.题目总结

用单栈可否实现后序遍历求深度

相关推荐
Codeking__18 分钟前
前缀和——中心数组下标
数据结构·算法
爱喝热水的呀哈喽29 分钟前
非线性1无修
算法
花火QWQ1 小时前
图论模板(部分)
c语言·数据结构·c++·算法·图论
Pacify_The_North1 小时前
【进程控制二】进程替换和bash解释器
linux·c语言·开发语言·算法·ubuntu·centos·bash
轮到我狗叫了1 小时前
力扣310.最小高度树(拓扑排序,无向图),力扣.加油站力扣.矩阵置零力扣.二叉树中的最大路径和
算法·leetcode·职场和发展
埃菲尔铁塔_CV算法2 小时前
深度学习驱动下的目标检测技术:原理、算法与应用创新(二)
深度学习·算法·目标检测
wuqingshun3141592 小时前
经典算法 (A/B) mod C
c语言·开发语言·c++·算法·蓝桥杯
白杆杆红伞伞2 小时前
04_决策树
算法·决策树·机器学习
爱coding的橙子2 小时前
算法刷题Day9 5.18:leetcode定长滑动窗口3道题,结束定长滑动窗口,用时1h
算法·leetcode·职场和发展
姬公子5212 小时前
leetcodehot100刷题——排序算法总结
数据结构·c++·算法·排序算法