Question
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.
Code
队列的方式
/**
* 队列的方式实现
*
* @param root
* @return
*/
public int minDepth1(TreeNode root) {
if (root == null) {
return 0;
}
int level = 0;
Queue<TreeNode> queues = new LinkedList<>();
queues.offer(root);
while (!queues.isEmpty()) {
level++;
int size = queues.size();
for (int i = 0; i < size; i++) {
TreeNode t = queues.poll();
if (t.left == null && t.right == null) {
return level;
}
if (t.left != null) {
queues.offer(t.left);
}
if (t.right != null) {
queues.offer(t.right);
}
}
}
return 0;
}
递归方式
public int minDepth(TreeNode root) {
if (root == null) {
return 0;
}
return dfs(root);
}
/**
* 递归的方式实现
*
* @param root
* @return
*/
public int dfs(TreeNode root) {
if (root == null) {
return 0;
}
if (root.left == null && root.right == null) {
return 1;
}
return Math.min(dfs(root.left), dfs(root.right)) + 1;
}