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

1- Write a method size that returns the total number of nodes in the tree. For e

ID: 3869494 • Letter: 1

Question

1-

Write a method size that returns the total number of nodes in the tree. For example, the following tree has a size of 8:

Assume that you are adding this method to the IntTree class as defined below:

-----------------------------------------------

2-

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:

-----------------------------------------------------

Write the elements of the tree below in the order they would be seen by a pre-order, in-order, and post-order traversal.

Sound F/X

3-

pre-order in-order post-order

Explanation / Answer

1-

If you want to go with an recursive solution then I think this code completely works-

int countnodes()

{

countnodes = 1;

if (this.getLeftChild() != null)

countnodes += this.getLeftChild().countnodes();

if (this.getRightChild() != null)

countnodes += this.getRightChild().count();

return countnodes;

}

And if you want to go with a non-recursive solution then following code will work fine-

int countnodes() {

   Stack<Tree> stack = new Stack<Tree>();

   stack.push(this);

   int counter = 0;

   while (!stack.empty()) {

       Tree t = stack.pop();

       counter++;

       Tree cha = getLeftTree();

       if (cha != null) stack.push(ch);

       cha = getRightTree();

       if (cha != null) stack.push(cha);

   }

   return counter;

}

Note-For other questions to be answered please provide as separate questions