How to save similar shaped binary trees in Java

Asked By 0 points N/A Posted on -
qa-featured

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.

SHARE
Best Answer by Guy V Mohr
Best Answer
Best Answer
Answered By 0 points N/A #167789

How to save similar shaped binary trees in Java

qa-featured

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!

Answered By 0 points N/A #167790

How to save similar shaped binary trees in Java

qa-featured

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.

Login/Register to Answer

Related Questions