Reputation: 61
I'm a fairly new beginner to java and was practicing some leetcode here: https://leetcode.com/problems/same-tree/
My solution to the question was:
class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
if (p == null && q == null){
return true;
}
return (p.val == q.val)&&(p != null && q != null)&&
isSameTree(p.left, q.left)&&
isSameTree(p.right, q.right);
}
}
and I just couldn't get it to work with it resulting in a nullpointer error. But then a mere switch of the conditional:
return (p != null && q != null)&&(p.val == q.val)&&
isSameTree(p.left, q.left)&&
isSameTree(p.right, q.right);
and all of a sudden it works. No idea why. I thought && was a logical and operator, and so A and B is the same as B and A ... what's going on?
Upvotes: 1
Views: 255
Reputation: 5707
In order && operator to retrieve true all conditions need to return true so we first check the left conditions and only if its true we check the all the rest one by one, If any condition fails we stop checking all others.
So in your case you need to get all the low complexity operation first
More reading about short circuit evaluation
https://en.m.wikipedia.org/wiki/Short-circuit_evaluation
Upvotes: 1
Reputation: 813
The && operator is stand for 'and' in logic, which returns true only if both of conditions are true. So, the left condition checked first, and if it is false, the right condition isn't checked. Because of that, I suggest you to put the conditions by this order (the higher in this order should be the left condition):
Upvotes: 1
Reputation: 182
In math or boolean algebra or whatever, the AND operator has the associative and the commutative properties, so math-wise, no.
However, most all programming languages use lazy evaluation for their Boolean and operators. If the first operand is false
and the operator is &&
, then why bother evaluating the second operand if you know it is just going to return false?
Using that, you can avoid errors (like the one you posted) by changing the order of the operands.
Like, if you wanted to avoid a object is undefined
error when trying to access an object's members, you can do if(object != undefined && object.isExample)
. If object
is undefined, then it it knows that that expression is false and quits there.
Upvotes: 1
Reputation: 4554
In most programming languages, the expressions are evaluated from left to right. In your earlier approach, p.val
may result in NullPointerException when p
is null. To avoid this, you should always check the null conditions before in your AND/OR expressions. Which is exactly what you did (without realizing I guess.).
Upvotes: 1