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

 

posted @ 2020-04-16 14:43  johnny_zhao  阅读(186)  评论(0编辑  收藏  举报