CODE
<span style="font-size:14px;">public class Solution {
public int maxDepth(TreeNode root) {
if(root == null)
return 0;
int lMax = maxDepth(root.left);
int rMax = maxDepth(root.right);
return 1+((lMax>rMax)?lMax:rMax);
}
}</span>核心思想
1 递归遍历所有节点
2 return 1+((lMax>rMax)?lMax:rMax);
(1) 1是指根结点
(2) 不能写成 return 1+ (lMax>rMax)?lMax:rMax; ,这里+运算符会影响三目运算符的正常使用,要养成勤加 ( ) 的习惯,避免一些未
知的危险。
return 1+ (lMax>rMax)?lMax:rMax;
本文介绍了一种通过递归算法来计算二叉树的最大深度的方法。核心思想为:递归遍历所有节点,并返回每个子树的最大深度加一(根节点)。注意:在返回值的表达式中正确使用括号确保逻辑清晰。
8239

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



