This problem gave me a hard time, basically what I missed is that the definition of the minimum depth. It should be “the shortest path from the root node down to the nearest leaf node.” Therefore if there is only a root and a node attached to it, the minimum depth will be 2 instead of 1.

The idea is recursion. Basically what I was thinking is do a tree traverse while keeping the minimum value, this is affected by the pocket algorithm I currently am studying. It turned out to be a much more effective way to do this.

```
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int minDepth(TreeNode root) {
return recursionStep(root);
}
public static int recursionStep(TreeNode root){
if(root == null) return 0;
int left = recursionStep(root.left);
int right = recursionStep(root.right);
//to the nearest leaf node!!!
if(left == 0) return right+1;
if(right == 0) return left+1;
return left < right? left+1 : right+1;
}
}
```

Advertisements