【问题标题】:How these two codes snippets are different?这两个代码片段有何不同?
【发布时间】:2021-10-06 14:23:01
【问题描述】:

第二个代码工作正常,而第一个代码每次都返回 0。为什么会这样?

在第一个代码 sn-p 中,我通过引用“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,L+R);

        return 1+Math.max(L,R);
    }
}

【问题讨论】:

    标签: java optimization binary-tree binary-search-tree


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-06
      • 1970-01-01
      • 1970-01-01
      • 2021-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-29
      相关资源
      最近更新 更多