二叉树的最大、最小深度
104.最大深度
class Solution {
public int maxDepth(TreeNode root) {
//结点为空返回0
if(root==null){
return 0 ;
}else{
//递归左子树
int ld = maxDepth(root.left);
//递归右子树
int rd = maxDepth(root.right);
//返回左右子树的最大深度+根节点
return Math.max(ld,rd)+1;
}
}
}
111.最小深度
class Solution {
public int minDepth(TreeNode root) {
//结点为空,返回(0)
if(root==null){
return 0 ;
}
//结点都为空,返回该节点(1)
if(root.left==null&&root.right==null){
return 1;
}
//结点的左结点为空,遍历右子树
if(root.left==null){
return minDepth(root.right)+1;
}
//结点的右结点为空,遍历左子树
if(root.right==null){
return minDepth(root.left)+1;
}
//返回左右子树最小深度,加上根节点
return Math.min(minDepth(root.left),minDepth(root.right))+1;
}
}
还没有评论,来说两句吧...