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.
java:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution
{
public int minDepth(TreeNode root)
{
if (root == null)
return 0;
Queue<TreeNode> queue = new LinkedList<>();
Queue<Integer> depth = new LinkedList<>();
queue.add(root);
depth.add(1);
while (!queue.isEmpty())
{
TreeNode currNode = queue.poll();
int currDepth = depth.poll();
if (currNode.left != null)
{
queue.add(currNode.left);
depth.add(currDepth+1);
}
if (currNode.right != null)
{
queue.add(currNode.right);
depth.add(currDepth+1);
}
if (currNode.left == null && currNode.right == null)
{
return currDepth;
}
}
return -1;
}
}