首页 > 其他 > 详细

111. Minimum Depth of Binary Tree

时间:2019-04-11 00:21:13      阅读:135      评论:0      收藏:0      [点我收藏+]

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;
        }

 

111. Minimum Depth of Binary Tree

原文:https://www.cnblogs.com/chucklu/p/10687035.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!