稀碎从零算法笔记Day23-LeetCode:二叉树的最大深度

题型:链表、二叉树的遍历

链接:104. 二叉树的最大深度 - 力扣(LeetCode)

来源:LeetCode

题目描述

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

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

题目样例

示例 1:

复制代码
输入:root = [3,9,20,null,null,15,7]
输出:3

示例 2:

复制代码
输入:root = [1,null,2]
输出:2

提示:

  • 树中节点的数量在 [0, 104] 区间内。
  • -100 <= Node.val <= 100

题目思路

最大深度跟高度数值一样

可以用【最大深度 = 左右子树的深度的最大值 + 1】------这里的1就是根节点占的一个深度

然后就是后续遍历递归了:MaxDepth(root->left) ,MaxDepth(root->right), root_depth = max(,)

递归结束条件就是:root == NULL

C++代码

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) {
    // 左右子树的最大深度+1 就是最大深度
    if(root == NULL)
        return 0;//递归结束条件,
    int max_deep;
    max_deep = max(maxDepth(root->left),maxDepth(root->right)) + 1;  
    return max_deep;  
    }
};

结算页面

相关推荐
NEFU_Jyj7 小时前
牛客周赛R168
算法
La Pulga10 小时前
【FreeRTOS源码学习笔记】任务延时列表
笔记·mcu·学习·嵌入式·freertos·实时操作系统
文丑颜不良啊14 小时前
LeetCode2221~2240题目解析
java·leetcode
Navigator_Z15 小时前
LeetCode //C - 1317. Convert Integer to the Sum of Two No-Zero Integers
c语言·算法·leetcode
Peter-OK15 小时前
PostgreSQL学习笔记(入门-进阶-精通说明)
笔记·学习·postgresql
D e re k ZH16 小时前
C++ 标准库算法全景指南
数据结构·c++·算法
冻柠檬飞冰走茶16 小时前
字母移动游戏题解:贪心求最长可保留连续子串(附 C 实现)
c语言·开发语言·数据结构·算法·动态规划
文丑颜不良啊17 小时前
LeetCode2161~2180题目解析
java·leetcode
雪落漂泊17 小时前
C++算法 二分查找篇(上)
开发语言·c++·算法