【LeetCode】 111. 二叉树的最小深度 递归方式 迭代方式

题目

在这里插入图片描述

递归方式

思路:
在这里插入图片描述
每个TreeNode有四种情况:
有右子树,没有左子树有左子树,没有右子树左右子树都有没有子树

我们要找的是最小深度,也就可以认为 没有子树 是循环的结尾

对于代码来说,也分为了这四种情况进行递归,这样一来就比较清楚了:
有右子树,没有左子树
直接将右节点作为根节点进行递归
有左子树,没有右子树
直接将左节点作为根节点进行递归
左右子树都有
分别以左节点和右节点分别作为根节点进行递归,取较小的一个
没有子树
直接返回本身的高度 1

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int minDepth(TreeNode root) {
        if (root == null)
            return 0;
        if (root.left == null && root.right != null)
            return minDepth(root.right) + 1;
        else if (root.left != null && root.right == null)
            return minDepth(root.left) + 1;
        else if (root.left != null && root.right != null)
            return Math.min(minDepth(root.left) + 1, minDepth(root.right) + 1);
        else
            return 1;
    }
}

迭代方式

迭代的方式其实就是二叉树的层级遍历,从第一层开始,一层层的向下找,直到找到一个左右子树都没有的节点为止就退出,思路很简单

  1. 定义一个记录层数的值
  2. 使用队列存储每层的节点,每遍历完一层,记录的层数加一,添加下一层的节点
  3. 判断每个节点是否有左右节点,如果没有,则返回层数
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int minDepth(TreeNode root) {
        int res = 0;
        if (root == null) return res;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            res ++;
            int size = queue.size(); // 这里的 size 记录的是每一层的节点的数量
            while (size > 0) {
                TreeNode node = queue.poll();
                if (node.left == null && node.right == null) return res;
                if (node.left != null) queue.add(node.left);
                if (node.right != null) queue.add(node.right);
                size--;
            }
        }
        return res;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Geek-Banana

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值