I was trying out the leetcode problem here
the code i wrote is
public int toLeaf(TreeNode j){
int ans=1;
try{
ans= Math.max(toLeaf(j.left),toLeaf(j.right))+1;
}catch(Exception e){
}
return ans;
}
public int diameterOfBinaryTree(TreeNode root) {
return toLeaf(root);
}
which gave me wrong answer but as soon as added a print statment i got correct answers on the sample testcases
public int toLeaf(TreeNode j){
int ans=1;
try{
ans= Math.max(toLeaf(j.left),toLeaf(j.right))+1;
}catch(Exception e){
}
System.out.println(j.val+" "+ans); //here
return ans;
}
public int diameterOfBinaryTree(TreeNode root) {
return toLeaf(root);
}
what is the reason behind this? here is the screenshot rejected
The printing is not the cause of the different behaviour but the access of
j.valis.If you had proper null-checks in your code, e.g.
if (j == null) { return 0; }in the beginning of the method this would not happen.In the first snippet if you call the method with
j = nullyou get an NPE in thetry, catch it, ignore it and then return 1. The caller will get the 1, add 1 and thenreturn 2.In the second snippet if you call the method with
j = nullyou once again get an NPE in the try, ignore it, then continue to theprintwhich raises another NPE which is then thrown from the method and the recursive caller will catch it and not perform theans = ... + 1successfully but simplyreturn 1.Therefore you have a different behaviour between the two snippets. But this is entirely unrelated to printing itself.