Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

JAVA: Consider the BinaryTree class partially given below. Add to the BinaryTree

ID: 3821862 • Letter: J

Question

JAVA: Consider the BinaryTree class partially given below. Add to the BinaryTree class a method Public boolean equals(Object T) which would return true if "this" tree is the same as T, otherwise it would return false.

public class BinaryTree{

public class TreeNode{

private data;

private TreeNode left;

private TreeNode right;

public TreeNode(E newData){

data = newData;
left = null;
right = null;

}

} // end

class TreeNode

private TreeNode root;

public BinaryTree(){

root = null; }

// other methods } // end class BinaryTree

Explanation / Answer

HI, Please find my implementation.

Please let me know in case of any issue.

public class BinaryTree{

   public class TreeNode{

       private int data;

       private TreeNode left;

       private TreeNode right;

       public TreeNode(int newData){

           data = newData;

           left = null;

           right = null;

       }

   } // end

   private TreeNode root;

   public BinaryTree(){

       root = null;

   }

   /* Given two trees, return true if they are

structurally identical */

   public boolean equals(Object T)

   {

       if(! (T instanceof BinaryTree))

           return false;

       BinaryTree other = (BinaryTree)T;

       TreeNode b = other.root; // root of other tree

       TreeNode a = this.root; // current tree root

      

       // calling identical function

       return identicalTrees(a, b);

      

   }

   /* Given two trees, return true if they are

structurally identical */

   private boolean identicalTrees(TreeNode a, TreeNode b)

   {

       /*1. both empty */

       if (a == null && b == null)

           return true;

       /* 2. both non-empty -> compare them */

       if (a != null && b != null)

           return (a.data == b.data

           && identicalTrees(a.left, b.left)

           && identicalTrees(a.right, b.right));

       /* 3. one empty, one not -> false */

       return false;

   }

   // other methods

} // end class BinaryTree