英文:
Does print statement in java effect any variables (without using increment)?
问题
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 statement i got correct answers on the sample test cases
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
英文:
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
答案1
得分: 1
打印不是不同行为的原因,而是对 j.val
的访问。
如果您在代码中进行了适当的空值检查,例如在方法开头使用 if (j == null) { return 0; }
,那么这种情况就不会发生。
在第一个片段中,如果您使用 j = null
调用该方法,您将在 try
中收到一个 NPE,然后捕获它,忽略它,然后返回 1。调用者将得到 1,加上 1,然后 return 2
。
在第二个片段中,如果您使用 j = null
调用该方法,您再次在 try 中得到一个 NPE,忽略它,然后继续到 print
,这会引发另一个 NPE,然后从方法中抛出,递归调用者将捕获它,并且 不会 成功执行 ans = ... + 1
,而只是简单地 return 1
。
因此,您在这两个片段之间有不同的行为。但这与打印本身完全无关。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论