首页 > 其他 > 详细

111. Minimum Depth of Binary Tree

时间:2020-04-16 14:55:30      阅读:77      评论:0      收藏:0      [点我收藏+]
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

原文:https://www.cnblogs.com/johnnyzhao/p/12712819.html

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