Description:
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.
Solution:
DFS即可。
import java.util.*;
public class Solution {
public int minDepth(TreeNode root) {
if (root == null)
return 0;
return depth(root);
}
int depth(TreeNode root) {
// if (root.left == null && root.right == null)
// return 1;
int ret = Integer.MAX_VALUE;
if (root.left != null)
ret = Math.min(depth(root.left), ret);
if (root.right != null)
ret = Math.min(depth(root.right), ret);
if (ret == Integer.MAX_VALUE)
ret = 1;
else
ret++;
return ret;
}
}