这两个代码片段有何不同?

第二个代码工作正常,而第一个代码每次都返回 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);
    }
}
zaoz123 回答:这两个代码片段有何不同?

在第一个示例中,您将 primitive 值传递给另一个方法并尝试在那里更改它,但它不起作用。

How to do the equivalent of pass by reference for primitives in Java

本文链接:https://www.f2er.com/5813.html

大家都在问