Given a binary tree, find its minimum depth.
class Solution {
public int minDepth(TreeNode root) {
if (root == null) {
return 0;
}
if (root.left == null && root.right == null) {
return 1;
}
int left = minDepth(root.left);
int right = minDepth(root.right);
if (root.left == null) {
return right + 1;
}
if (root.right == null) {
return left + 1;
}
return Math.min(left, right) + 1;
}
}
```java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
class Step {
TreeNode node;
int level;
Step(TreeNode node, int level) {
this.node = node;
this.level = level;
}
}
public int minDepth(TreeNode root) {
Queue<Step> queue = new LinkedList<>();
if (root == null) {
return 0;
}
queue.offer(new Step(root, 0));
int min = Integer.MAX_VALUE;
while (!queue.isEmpty()) {
Step cur = queue.poll();
TreeNode node = cur.node;
if (node == null) {
continue;
}
if (node.left == null && node.right == null) {
min = Math.min(min, cur.level+1);
}
queue.offer(new Step(node.left, cur.level+1));
queue.offer(new Step(node.right, cur.level+1));
}
return min;
}
}
```