LeetCode-111. 二叉树的最小深度

不念不忘少年蓝@ 2024-03-27 15:57 194阅读 0赞

目录

    • 题目分析
    • 递归法

题目来源
111. 二叉树的最小深度

题目分析

这道题目容易联想到104题的最大深度,把代码搬过来

  1. class Solution {
  2. public int minDepth(TreeNode root) {
  3. return dfs(root);
  4. }
  5. public static int dfs(TreeNode root){
  6. if(root == null){
  7. return 0;
  8. }
  9. int left = dfs(root.left);
  10. int right = dfs(root.right);
  11. return Math.min(left,right)+1;
  12. }
  13. }

在这里插入图片描述
然后仔细读题
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
在这里插入图片描述
在这里插入图片描述
为了满足题目需求, 需要额外加上一个条件

  1. if(root.left == null && root.right != null)
  2. if(root.left != null && root.right == null)

递归法

递归三部曲

  • 1.确定递归函数的参数和返回值

参数为要传入的二叉树根节点,返回的是int类型的深度。
代码如下:

  1. int dfs(TreeNode root)
  • 2.确定终止条件

终止条件也是遇到空节点返回0,表示当前节点的高度为0。
代码如下:

  1. if(root == null){
  2. return 0;
  3. }
  • 3.确定单层递归的逻辑

这块和求最大深度可就不一样了
如果左子树为空,右子树不为空,说明最小深度是 1 + 右子树的深度。
反之,右子树为空,左子树不为空,最小深度是 1 + 左子树的深度。 最后如果左右子树都不为空,返回左右子树深度最小值 + 1 。

  1. int leftDepth = dfs(root.left); // 左
  2. int rightDepth = dfs(root.right); // 右
  3. // 中
  4. // 当一个左子树为空,右不为空,这时并不是最低点
  5. if(root.left == null && root.right != null){
  6. return rightDepth + 1;
  7. }
  8. // 当一个右子树为空,左不为空,这时并不是最低点
  9. if(root.left != null && root.right == null){
  10. return leftDepth + 1;
  11. }
  12. return Math.min(leftDepth,rightDepth)+1;

遍历的顺序为后序(左右中),可以看出:求二叉树的最小深度和求二叉树的最大深度的差别主要在于处理左右孩子不为空的逻辑。
整体递归代码

  1. class Solution {
  2. public int minDepth(TreeNode root) {
  3. if(root == null){
  4. return 0;
  5. }
  6. return dfs(root);
  7. }
  8. public static int dfs(TreeNode root){
  9. if(root == null){
  10. return 0;
  11. }
  12. int leftDepth = dfs(root.left); // 左
  13. int rightDepth = dfs(root.right); // 右
  14. // 中
  15. // 当一个左子树为空,右不为空,这时并不是最低点
  16. if(root.left == null && root.right != null){
  17. return rightDepth + 1;
  18. }
  19. // 当一个右子树为空,左不为空,这时并不是最低点
  20. if(root.left != null && root.right == null){
  21. return leftDepth + 1;
  22. }
  23. return Math.min(leftDepth,rightDepth)+1;
  24. }
  25. }

在这里插入图片描述

发表评论

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

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

相关阅读