
class Solution {
public int maxDepth(TreeNode root) {
if(root==null){
return 0;
}
else{
int leftTreeDepth=maxDepth(root.left);
int rightTreeDepth=maxDepth(root.right);
return java.lang.Math.max(leftTreeDepth,rightTreeDepth)+1;
}
}
}
解题思路
解决最大深度就是看左/右子树最深能到多深,那么就直接设两个成员变量作为两者的深度,然后直接调用Math.max(a,b)函数,然后就知道a,b哪个更大,最后要注意得到的值要+1,应该一开始定义树的深度为1
本文详细解析了计算二叉树最大深度的递归算法,通过递归调用左右子树的最大深度,并使用Math.max函数确定两者中较大值,最终返回最大深度加一的结果。该算法适用于计算机科学和数据结构学习。
209

被折叠的 条评论
为什么被折叠?



