求二叉树中的最大深度和最小深度Java

最大深度

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;
	}
}

猜你喜欢

转载自blog.csdn.net/sinat_40553837/article/details/88718177