111. Minimum Depth of Binary Tree

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.csdn.net/u011475210/article/details/79278219

 

作者:Chuck Lu    GitHub    
posted @   ChuckLu  阅读(143)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2018-04-10 设置断点后,查看堆栈信息,判断错误调用的来源是哪里
点击右上角即可分享
微信分享提示