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