class Solution {
private int d;
public int diameterOfBinaryTree(TreeNode root) {
d = 0;
maxPath(root);
return d ;
}
private int maxPath (TreeNode node){
if (node == null) {return 0;}
int leftDepth = maxPath(node.left);
int rightDepth= maxPath(node.right);
// d = Math.max(d,leftDepth + rightDepth );
if (d < leftDepth + rightDepth) {d = leftDepth + rightDepth;}
return Math.max(leftDepth, rightDepth) +1;
}
}
在第二行中;私有int d";必须写在BinaryTree((的直径之前????我可以把它设置为公开的吗??
private
、public
和protected
修饰符应用于成员,而不是局部变量(在定义它们的范围之外无法访问(。
如果希望d
可以从其他类访问,而不仅仅是从Solution
的方法内部访问,则可以将其设置为public
。