111. Minimum Depth of Binary Tree

Posted johnnyzhao

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了111. Minimum Depth of Binary Tree相关的知识,希望对你有一定的参考价值。

import java.util.*

class Solution {
    fun minDepth(root: TreeNode?): Int {
        if (root == null) {
            return 0
        }
        var depth = 0
        //LinkedList实现了Queue接口,可以用作队列使用
        val queue = LinkedList<TreeNode>()
        queue.offer(root)
        while (queue.size > 0) {
            depth++
            val size = queue.size
            for (i in size - 1 downTo 0) {
                val node = queue.poll()
                //if found out the first leaf, return the depth
                //leaf is a node with no children
                if (node.left == null && node.right == null) {
                    return depth
                }
                if (node.left != null) {
                    queue.offer(node.left)
                }
                if (node.right != null) {
                    queue.offer(node.right)
                }
            }
        }
        return -1
    }
}

 

以上是关于111. Minimum Depth of Binary Tree的主要内容,如果未能解决你的问题,请参考以下文章

111. Minimum Depth of Binary Tree

111.minimum depth of binary tree(E)

111. Minimum Depth of Binary Tree

111. Minimum Depth of Binary Tree

111. Minimum Depth of Binary Tree

[LeetCode]题解(python):111 Minimum Depth of Binary Tree