自己的代码:
Runtime: 0 ms, faster than 100.00% of Java online submissions for Minimum Depth of Binary Tree.
Memory Usage: 40.2 MB, less than 5.41% of Java online submissions for Minimum Depth of Binary
public static int minDepth(TreeNode root) {
if(root == null) return 0;
int[] result = new int[1]; // 全局变量,更新最小值
result[0] = Integer.MAX_VALUE; // 求最小值,则需要预置Integer.MAX_VALUE
depthHelper(root,1,result);
return result[0];
}
public static void depthHelper(TreeNode root,int depth,int[] result) {
if(root != null && root.left == null && root.right == null) { // 必须为叶子节点
if( depth<result[0] ) {
result[0] = depth;
}
return;
}
if(root.left != null) { // 非空判断
depthHelper(root.left,depth+1,result);
}
if(root.right != null) {
depthHelper(root.right,depth+1,result);
}
}