二叉树——111. 二叉树的最小深度

偏执的太偏执、 2023-10-08 16:12 110阅读 0赞

1 题目描述

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

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

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

2 题目示例

在这里插入图片描述
示例 2:

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

3 题目提示

树中节点数的范围在 [0, 105] 内
-1000 <= Node.val <= 1000

4 思路

方法一:深度优先搜索
首先可以想到使用深度优先搜索的方法,遍历整棵树,记录最小深度。
对于每一个非叶子节点,我们只需要分别计算其左右子树的最小叶子节点深度。这样就将一个大问题转化为了小问题,可以递归地解决该问题。
复杂度分析
时间复杂度:O(N),其中N是树的节点数。对每个节点访问一次。
·空间复杂度:O(H),其中H是树的高度。空间复杂度主要取决于递归时栈空间的开销,最坏情况下,树呈现链状,空间复杂度为O(N)。平均情况下树的高度与节点数的对数正相关,空间复杂度为O(log N)。
方法二:广度优先搜索
同样,我们可以想到使用广度优先搜索的方法,遍历整棵树。当我们找到一个叶子节点时,直接返回这个叶子节点的深度。广度优先搜索的性质保证了最先搜索到的叶子节点的深度—定最小。
复杂度分析
时间复杂度:O(N),其中N是树的节点数。对每个节点访问一次。
·空间复杂度:O(N),其中N是树的节点数。空间复杂度主要取决于队列的开销,队列中的元素个数不会超过树的节点数。

5 我的答案

方法一:深度优先搜索

  1. class Solution {
  2. public int minDepth(TreeNode root) {
  3. if (root == null) {
  4. return 0;
  5. }
  6. if (root.left == null && root.right == null) {
  7. return 1;
  8. }
  9. int min_depth = Integer.MAX_VALUE;
  10. if (root.left != null) {
  11. min_depth = Math.min(minDepth(root.left), min_depth);
  12. }
  13. if (root.right != null) {
  14. min_depth = Math.min(minDepth(root.right), min_depth);
  15. }
  16. return min_depth + 1;
  17. }
  18. }

方法二:广度优先搜索

  1. class Solution {
  2. class QueueNode {
  3. TreeNode node;
  4. int depth;
  5. public QueueNode(TreeNode node, int depth) {
  6. this.node = node;
  7. this.depth = depth;
  8. }
  9. }
  10. public int minDepth(TreeNode root) {
  11. if (root == null) {
  12. return 0;
  13. }
  14. Queue<QueueNode> queue = new LinkedList<QueueNode>();
  15. queue.offer(new QueueNode(root, 1));
  16. while (!queue.isEmpty()) {
  17. QueueNode nodeDepth = queue.poll();
  18. TreeNode node = nodeDepth.node;
  19. int depth = nodeDepth.depth;
  20. if (node.left == null && node.right == null) {
  21. return depth;
  22. }
  23. if (node.left != null) {
  24. queue.offer(new QueueNode(node.left, depth + 1));
  25. }
  26. if (node.right != null) {
  27. queue.offer(new QueueNode(node.right, depth + 1));
  28. }
  29. }
  30. return 0;
  31. }
  32. }

发表评论

表情:
评论列表 (有 0 条评论,110人围观)

还没有评论,来说两句吧...

相关阅读