求出二叉树的最小深度;
分析:
空树:1
只有根:1
只有左子树或只有右子树:子树深度+1;
既有左,又有右子树:min(左右子树深度)+1;
实现:
public int minDepth(Node root){
if(root==null){
return 0;
}
int ldp=minDepth(root.left);
int rdp=minDepth(root.right);
if(root.left==null){
return rdp+1;
}
if(root.right==null){
return ldp+1;
}
return min(ldp+1,rdp+1);
}
private int min(int i, int j) {
return i<j?i:j;
}