# Binary Tree Min Depth - Breadth First Search / BFS on Tree

There’s a problem of the answer of test case 1, it should be 5 instead of 2. As node 2 had two children 4 and 5, it is not a leave node.

the question doesn’t explicitly state it but you should return the depth, not the node itself

1 Like
``````we could also keep track of the depth in the q itself
``````

q = deque([[root, 0]])

``````while q:

node, level = q.popleft()

if not node.left and not node.right:

return level

if node.left:

q.append([node.left, level + 1])

if node.right:

q.append([node.right, level + 1])
``````

for any go people:

``````type NodeQueue []Node

func (q *NodeQueue) Enqueue(n Node) {
*q = append(*q, n)
}

func (q *NodeQueue) Dequeue() Node {
el := (*q)
*q = (*q)[1:]

return el
}

func isLeafNode(n Node) bool {
if n.left == nil && n.right == nil {
return true
}

return false
}

func binaryTreeMinDepth(root *Node) int {
result := 0

if root == nil {
return result
}

var q NodeQueue
q.Enqueue(*root)

for len(q) > 0 {
size := len(q)

for i := 0; i < size; i++ {
current := q.Dequeue()

if isLeafNode(current) {
return result
}

if current.left != nil {
q.Enqueue(*current.left)
}
if current.right != nil {
q.Enqueue(*current.right)
}
}

result++
}

return result
}
``````

Could you at least better explain the output of the problem?
I want to try it myself without looking at the solution, but there’s barely anything…

Did you look at the picture? They want us to look for the smallest depth of a branch of the tree. If you been following in order you should have seen a tree section where it explains all the definition.

Is the final `return depth` needed? The early return should catch all cases right?