How to save similar shaped binary trees in Java
Hi guys, I am learning to code in Java. However, I am having a problem with three binary trees. How do I save shapes in binary java coding to ensure that the trees have the same shape? Thank you.
Hi guys, I am learning to code in Java. However, I am having a problem with three binary trees. How do I save shapes in binary java coding to ensure that the trees have the same shape? Thank you.
Hello! If you want to create similar shape of binary tree, you have to maintain a CODE. The CODE is here:
boolean equalTrees(Node lhs, Node rhs)
{
   // Empty trees are equal
   if (lhs == null && rhs == null)
       return true;
   // Empty tree is not equal to a non-empty one
   if ((lhs == null && rhs != null)
       || (lhs != null && rhs == null))
       return false;
   // otherwise check recursively
   return equalTrees(lhs.left(), rhs.left())
       && equalTrees(lhs.right(), rhs.right())
}
I think you have got it. Have a nice time!
Hello,
If the structures of binary trees are equal, you can check it by converting each tree to an array and then compare the arrays elements. If the size of the two arrays are equal, then compare the data of each cell. If the size of the two arrays are unequal then you have to do nothing cause two different sizes of array cannot have same structure.
Hope, you get the point. Thanks.