求二叉树中的最大深度和最小深度Java
作者:
Solang | 来源:发表于
2020-12-25 11:12 被阅读0次
最大深度
public int maxDepth(TreeNode root){
if(root==null) return 0;
else{
int m = maxDepth(root.left);
int n = maxDepth(root.right);
return (m>n?m:n) +1;
}
}
最小深度
public int minDepth(TreeNode root){
if(root==null) return 0;
if(root.left==null) return minDepth(root.right);//左边为空,取右边的深度
if(root.right==null) return minDepth(root.left);//右边为空,取左边的深度
else{
int m = minDepth(root.left);
int n = minDepth(root.right);
return (m<n?m:n) +1;
}
}
本文标题:求二叉树中的最大深度和最小深度Java
本文链接:https://www.haomeiwen.com/subject/kwpbnktx.html
网友评论