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.val
is.
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 = null
you get an NPE in the try
, catch it, ignore it and then return 1. The caller will get the 1, add 1 and then return 2
.
In the second snippet if you call the method with j = null
you once again get an NPE in the try, ignore it, then continue to the print
which raises another NPE which is then thrown from the method and the recursive caller will catch it and not perform the ans = ... + 1
successfully but simply return 1
.
Therefore you have a different behaviour between the two snippets. But this is entirely unrelated to printing itself.