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.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private int minDepth = Integer.MAX_VALUE;
public int minDepth(TreeNode root) {
if(root == null){
return 0;
}
runCore(root,1);
return minDepth;
}
private void runCore(TreeNode root,int depth){
if(root == null) return;
if(root.left ==null && root.right == null){
if(minDepth>depth){
minDepth = depth;
}
}
runCore(root.left,depth+1);
runCore(root.right,depth+1);
}
}