I'm looking at some Java algorithm examples and I come across this snippet code within a recursive method:
boolean subTree(TreeNode t1, TreeNode t2) {
if (t1 == null) {
return false;
}
if (t1.value == t2.value) {
if (treeMatch(t1, t2))
return true;;
}
return (subTree(t1.left, t2) || subTree(t1.right, t2));
}
Not knowing (and never seeing) || being used within a return statement before, let alone a recursive one, really made me confused. I copied the code into Eclipse to see if it was valid and it was. I then replaced the || with && and Eclipse didn't seem bothered by it. Logically, I understand that this recursive code is supposed to continue down the left and right subtrees of TreeNode t1, but I'm looking for a more theoretical explanation behind how this Java syntax works.
Can someone explain the meaning behind || and && within Java's return statement? What does it mean in terms of recursion? Is it only meaningful when used in conjunction with recursion?
Developers use Java to construct applications in laptops, data centres, game consoles, scientific supercomputers, cell phones, and other devices. Java is the worlds third most popular programming language, after Python and C - according to the TIOBE index, which evaluates programming language popularity.
Java is a programming language and computing platform first released by Sun Microsystems in 1995. It has evolved from humble beginnings to power a large share of today's digital world, by providing the reliable platform upon which many services and applications are built.
Java, also spelled Djawa or Jawa, island of Indonesia lying southeast of Malaysia and Sumatra, south of Borneo (Kalimantan), and west of Bali. Java is home to roughly half of Indonesia's population and dominates the country politically and economically.
Java is a popular programming language, created in 1995. It is owned by Oracle, and more than 3 billion devices run Java. It is used for: Mobile applications (specially Android apps)
As defined in the method signature, you will have to return a boolean
. Therefore, after the return
keyword, you will have to provide a boolean
or an expression which is evaluated to boolean
.
In your case you have the expession (subTree(t1.left, t2) || subTree(t1.right, t2));
in which the two operands will be evaluated to boolean
and you will apply an logical OR
on them only if the first evaluates to false
. If the first operand evaluates to true
the second will not be evaluated and true
will be retured.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With