104. 二叉树的最大/最小深度

本文详细介绍了两种计算二叉树深度的方法:递归和层序遍历。对于最大深度,分别展示了如何通过递归和广度优先搜索找到二叉树的最大层级。对于最小深度,同样提供了递归和层序遍历的解决方案,特别关注了当左右子树为空时的特殊情况。这些算法对于理解和操作二叉树结构至关重要。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

104. 二叉树的最大深度

①递归求最大深度

class Solution {
    public int maxDepth(TreeNode root) {  //二叉树的最大深度
        if (root == null) {
            return 0;
        }
        return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
    }
}

②层序遍历求最大深度

class Solution {
    public int maxDepth(TreeNode root) {  层序遍历模板
        if (root == null)   return 0;
        Queue<TreeNode> que = new LinkedList<>();
        que.offer(root);
        int depth = 0;
        while (!que.isEmpty())
        {
            int len = que.size();
            while (len > 0)
            {
                TreeNode node = que.poll();
                if (node.left != null)  que.offer(node.left);
                if (node.right != null) que.offer(node.right);
                len--;
            }
            depth++;
        }
        return depth;
    }
}

111. 二叉树的最小深度

①递归求二叉树的最小深度

重点在递归终止条件。

class Solution {
    public int minDepth(TreeNode root) {  //深度遍历 + 递归
        if (root == null)  return 0;
        int left = minDepth(root.left);
        int right = minDepth(root.right);
        return left == 0 || right == 0 ? 1 + left + right : 1 + Math.min(left, right);
    }
}

②层序遍历求最小深度

创建QueueNode(TreeNode node, int depth),利用队列,遇到左右孩子都为null的时候即可返回depth。

class Solution {
    class QueueNode {
        TreeNode node;
        int depth;
        public QueueNode(TreeNode node, int depth) {
            this.node = node;
            this.depth = depth;
        }
    }
    public int minDepth(TreeNode root) {
        if (root == null)   return 0;
        Queue<QueueNode> queue = new LinkedList<QueueNode>();
        queue.offer(new QueueNode(root, 1));
        while (!queue.isEmpty()) {
            QueueNode nodeDepth = queue.poll();
            TreeNode node = nodeDepth.node;
            int depth = nodeDepth.depth;
            if (node.left == null && node.right == null)  return depth;
            if (node.left != null)  queue.offer(new QueueNode(node.left, depth + 1));
            if (node.right != null)  queue.offer(new QueueNode(node.right, depth + 1));
        }
        return 0;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值