• ㊗️
• 大家
• offer
• 多多！

## Problem

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.

Note: A leaf is a node with no children.

Example:

Given binary tree [3,9,20,null,null,15,7],

    3
/ \
9  20
/  \
15   7


return its minimum depth = 2.

## Code

class Solution {
public int minDepth(TreeNode root) {
if(root == null) return 0;

if(root.left == null || root.right == null){
// 要找到leaf才算最小深度, 因此取最大才能找到leaf
return 1 + Math.max(minDepth(root.left), minDepth(root.right));
}

return 1 + Math.min(minDepth(root.left), minDepth(root.right));
}
}


class Solution {
public int minDepth(TreeNode root) {
if(root == null) return 0;

queue.offer(root);

int res = 1;
while(!queue.isEmpty()){
int size = queue.size();
for(int i = 0; i < size; i++){
TreeNode node = queue.poll();
if(node.left == null && node.right == null) return res;

if(node.left != null){
queue.offer(node.left);
}

if(node.right != null){
queue.offer(node.right);
}
}

res++;
}
return -1;
}
}