第二个代码工作正常,而第一个代码每次都返回 0。为什么会这样?
在第一个代码片段中,我通过引用 'height' 方法传递 'ans' 变量,该方法假设修改传递的 'ans' 变量。
class Solution {
public int diameterOfBinaryTree(TreeNode root) {
int ans=0;
if(root==null)return 0;
height(root,ans);
return ans;
}
public int height(TreeNode root,int ans){
if(root==null)return 0;
int L=height(root.left,ans);
int R=height(root.right,ans);
ans = Math.max(ans,L+R);
return 1+Math.max(L,R);
}
}
下面的代码工作正常。
class Solution {
int ans=0;
public int diameterOfBinaryTree(TreeNode root) {
if(root==null )return 0;
height(root);
return ans;
}
public int height(TreeNode root){
if(root==null)return 0;
int L=height(root.left);
int R=height(root.right);
ans=Math.max(ans,R);
}
}