213k views
5 votes
Write a method equals that could be added to the IntTree class. (On your handout this method is called "equals", but Practice-It needs to use the name "equals" for another purpose, so we'll call it "equals2" here.) The method accepts another binary tree of integers as a parameter and compares the two trees to see if they are equal to each other. For example, if variables of type IntTree called t1 and t2 have been initialized, then the call of t1.equals2(t2) will return true if the trees are equal and false if otherwise.Two trees are considered equal if they have exactly the same structure and store the same values. Each node in one tree must have a corresponding node in the other tree in the same location relative to the root and storing the same value. Two empty trees are considered equal to each other.You may define private helper methods to solve this problem, but otherwise you may not call any other methods of the class nor create any data structures such as arrays, lists, etc. Your method should not change the structure or contents of either of the two trees being compared.Assume that you are adding this method to the IntTree class as defined below:public class IntTree { private IntTreeNode overallRoot; ...}

User TimHorton
by
6.7k points

1 Answer

6 votes

Answer:

public boolean equals(Object other)

{

// check correct instance

if (other instanceof IntTree)

{

try

{

IntTree otherTree = (IntTree) other;

return equals(overallRoot, otherTree.overallRoot);

}

// caught exceptions

catch (Exception e)

{

return false;

}

}

return false;

}

public boolean equals(IntTreeNode tree1, IntTreeNode tree2)

{

// if reach ends

if (tree1 == null && tree2 == null)

{

// they are equal

return true;

}

else if (tree1 == null || tree2 == null)

{

// not equal

return false;

}

// check left part

boolean leftPart = equals(tree1.left, tree2.left);

// check current element is same

boolean currentPart = tree1.element.equals(tree2.element);

// check right part

boolean rightPart = equals(tree1.right, tree2.right);

// all are equal

return (leftPart && currentPart && rightPart);

}

Step-by-step explanation:

User Allohvk
by
6.2k points