【力扣】104. 二叉树的最大深度、111. 二叉树的最小深度

104. 二叉树的最大深度

题目描述

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

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

示例 1:

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

输出:3

示例 2:

输入:root = 1,null,2

输出:2

提示:

  • 树中节点的数量在 0, 10^4^ 区间内。
  • -100 <= Node.val <= 100

解题方法

  • C 深度优先搜索------递归
c 复制代码
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
int my_max(int a, int b) {
    if (a > b)
        return a;
    else
        return b;
}

int maxDepth(struct TreeNode* root) {
    if (NULL == root) {
        return 0;
    }
    int left = maxDepth(root->left);
    int right = maxDepth(root->right);
    return my_max(left, right) + 1;
}

复杂度分析

时间复杂度:O(n),其中 n 为二叉树节点的个数。

空间复杂度:O(h),其中 h表示二叉树的高度。递归函数需要栈空间,而栈空间取决于递归的深度,因此空间复杂度等价于二叉树的高度。


111. 二叉树的最小深度

题目描述

给定一个二叉树,找出其最小深度。

最小深度是从根节点到最近叶子节点的最短路径上的节点数量。

说明:叶子节点是指没有子节点的节点。

示例 1:

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

输出:2

示例 2:

输入:root = 2,null,3,null,4,null,5,null,6

输出:5

提示:

  • 树中节点数的范围在 0, 10^5^ 内
  • -1000 <= Node.val <= 1000

解题方法

  • C 深度搜索------递归
c 复制代码
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
int my_min(int a, int b) {
    if (a > b)
        return b;
    else
        return a;
}

int minDepth(struct TreeNode* root) {
    if (NULL == root) {
        return 0;
    }
    if (NULL == root->left && NULL == root->right) {
        return 1;
    }

    int min_depth = INT_MAX;
    if (NULL != root->left) {
        min_depth = my_min(minDepth(root->left), min_depth);
    }

    if (NULL != root->right) {
        min_depth = my_min(minDepth(root->right), min_depth);
    }

    return min_depth + 1;
}

复杂度分析

时间复杂度:O(N),其中 N 是树的节点数。对每个节点访问一次。

空间复杂度:O(H),其中 H 是树的高度。空间复杂度主要取决于递归时栈空间的开销,最坏情况下,树呈现链状,空间复杂度为 O(N)。平均情况下树的高度与节点数的对数正相关,空间复杂度为 O(log⁡N)。

参考@力扣官方题解

相关推荐
octopus_c8 小时前
STL 之 string:auto 与范围 for、常用接口、模拟实现与深浅拷贝
开发语言·c++·算法
文丑颜不良啊19 小时前
LeetCode1941~1960题目解析
java·leetcode
MUSHANGXS1 天前
大模型时代的新蓝海-基于OS底层的AI-Agent应用
人工智能·职场和发展·交互
老师我太想进步了20261 天前
【数据结构-4】算法美学之顺序表
数据结构·算法
风影同志783241 天前
编码器是激活函数吗?—— 一个看起来很像、其实不是的类比
算法
UIU1141 天前
P1481 魔族密码
c++·算法·动态规划
文丑颜不良啊1 天前
LeetCode1961~1980题目解析
java·leetcode
文丑颜不良啊1 天前
LeetCode2001~2020题目解析
java·leetcode
加宝的起点雷达1 天前
40 条候选里 38 条来自同一个源,主卡整屏重样
人工智能·算法·创业