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

104. 二叉树的最大深度

题目描述

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

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

示例 1:

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

输出:3

示例 2:

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

输出:2

提示:

  • 树中节点的数量在 [0, 104] 区间内。
  • -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, 105] 内
  • -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)。

参考@力扣官方题解

相关推荐
沉默-_-几秒前
力扣hot100双指针专题解析2(C++)
java·c++·算法·蓝桥杯·双指针
福楠2 分钟前
C++ | 红黑树
c语言·开发语言·数据结构·c++·算法
程序员杰哥3 分钟前
Pytest自动化测试框架实战
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·pytest
丝瓜蛋汤4 分钟前
Proof of the contraction mapping theorem
人工智能·算法
We་ct23 分钟前
LeetCode 58. 最后一个单词的长度:两种解法深度剖析
前端·算法·leetcode·typescript
小袁顶风作案25 分钟前
leetcode力扣——452. 用最少数量的箭引爆气球
学习·算法·leetcode·职场和发展
deep_drink28 分钟前
【经典论文精读(一)】Isomap:非线性降维的全局几何框架(Science 2000)
人工智能·算法·机器学习
mjhcsp1 小时前
莫比乌斯反演总结
c++·算法
爱编码的傅同学1 小时前
【今日算法】LeetCode 25.k个一组翻转链表 和 43.字符串相乘
算法·leetcode·链表
stolentime1 小时前
P14978 [USACO26JAN1] Mooclear Reactor S题解
数据结构·c++·算法·扫描线·usaco