111. Minimum Depth of Binary Tree

本文探讨了在二叉树中寻找最小深度的有效算法。通过深度优先搜索(DFS)和广度优先搜索(BFS),详细解释了如何计算从根节点到最近叶子节点的最短路径。提供了递归和非递归的实现方式,并附有代码示例。

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

Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

Note: A leaf is a node with no children.

Example:

Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its minimum depth = 2.

 使用递归来做

1.如果当前结点,为null。那么最小深度depth为0

2.如果当前结点不为null,那么最小深度为1

   2.1 如果左结点和右结点都为null,那么到此结束,直接返回最小深度为1

   2.2 如果左结点和右结点都不为null,那么需要分别计算左结点和右结点的最小深度,取较小值+1

   2.3 如果左结点不为null,右结点为null,那么左结点的最小深度+1就作为,最小深度

   2.4 如果右结点不为null,左结点为null,那么右结点的最小深度+1就作为,最小深度

public int MinDepth(TreeNode root)
        {
            if (root == null)
            {
                return 0;
            }

            TreeNode left = root.left;
            TreeNode right = root.right;
            if (left == null && right == null)
            {
                return 1;
            }

            int depth;
            if (left != null && right != null)
            {
                int leftDepth = MinDepth(left);
                int rightDepth = MinDepth(right);
                depth = Math.Min(leftDepth, rightDepth);
            }
            else if (left != null)
            {
                depth = MinDepth(left);
            }
            else
            {
                depth = MinDepth(right);
            }

            return depth + 1;
        }

 

简化版的

 public int MinDepth(TreeNode root)
        {
            if (root == null)
            {
                return 0;
            }

            TreeNode left = root.left;
            TreeNode right = root.right;

            if (left == null)
            {
                return MinDepth(right) + 1;
            }

            if (right == null)
            {
                return MinDepth(left) + 1;
            }

            int leftDepth = MinDepth(left);
            int rightDepth = MinDepth(right);
            return Math.Min(leftDepth, rightDepth) + 1;
        }

 

上面的解题思路,是深度优先。

另外还有广度优先的算法

https://blog.youkuaiyun.com/u011475210/article/details/79278219

 

转载于:https://www.cnblogs.com/chucklu/p/10687035.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值