0

The second code is working fine whereas the first code is returning 0 every time. Why is it so?

In the first code snippet I am passing 'ans' variable by reference to the 'height' method, which suppose to modify passed 'ans' variable.

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);
    }
}

Below code works fine.

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);
    }
}
jerry22
  • 47
  • 4

1 Answers1

1

In first example you are passing primitive value to another method and trying to change it there, it won't work.

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

vszholobov
  • 2,133
  • 1
  • 8
  • 23