LeetCode 111. Minimum Depth of Binary Tree(二叉树的最小深度)

174 阅读1分钟

leetcode.com/problems/mi…

Discuss:www.cnblogs.com/grandyang/p…

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 1:

Input: root = [3,9,20,null,null,15,7]
Output: 2

Example 2:

Input: root = [2,null,3,null,4,null,5,null,6]
Output: 5

 

Constraints:

  • The number of nodes in the tree is in the range [0, 105].
  • -1000 <= Node.val <= 1000

解法一:

二叉树的经典问题之最小深度问题就是就最短路径的节点个数,还是用深度优先搜索 DFS 来完成。首先判空,若当前节点不存在,直接返回0。然后看若左子节点不存在,那么对右子节点调用递归函数,并加1返回。反之,若右子节点不存在,那么对左子节点调用递归函数,并加1返回。若左右子节点都存在,则分别对左右子节点调用递归函数,将二者中的较小值加1返回即可,参见代码如下:

class Solution {
    fun minDepth(root: TreeNode?): Int {
        if (root == null) {
            return 0
        }

        if (root.left == null) {
            return 1 + minDepth(root.right)
        }
        if (root.right == null) {
            return 1 + minDepth(root.left)
        }

        return 1 + minDepth(root.left).coerceAtMost(minDepth(root.right))
    }
}
class Solution {
    fun minDepth(root: TreeNode?): Int {
        if (root == null) {
            return 0
        }
        val leftDepth = minDepth(root.left)
        val rightDepth = minDepth(root.right)
        return if (leftDepth == 0 || rightDepth == 0) {
            leftDepth + rightDepth + 1
        } else {
            1 + leftDepth.coerceAtMost(rightDepth)
        }
    }
}

解法二:

也可以使用 BFS 来求解,层次遍历二叉树,记录当前层级,一旦遍历到第一个叶结点,就将当前层级数返回,即为该二叉树的最小深度。

class Solution {
    fun minDepth(root: TreeNode?): Int {
        if (root == null) {
            return 0
        }
        var result = 0
        val queue = LinkedList<TreeNode>()
        queue.offer(root)
        kotlin.run run@{
            while (queue.isNotEmpty()) {
                result++
                for (index in 0 until queue.size) {
                    val currentNode = queue.poll()
                    if (currentNode.left == null && currentNode.right == null) {
                        return@run
                    }
                    currentNode.left?.let {
                        queue.offer(it)
                    }
                    currentNode.right?.let {
                        queue.offer(it)
                    }
                }
            }
        }
        return result
    }
}