Oh I need serious help Add a method int getSize to BinaryTre
Oh I need serious help!
Add a method int getSize() to BinaryTree that returns the size of the binary tree where the size of the tree is defined to be the number of nodes. Here is how I want you to implement this method. Write a local class in getSize() named Counter which implements the BinaryTree Visitor interface:
The Counter constructor initializes mCount to 0. visit() simply increments mCount when it is called. Once the local class is completed, we can count the nodes in the tree by performing a traversal (it does not matter which type of traversal we performe because each node will be visited during the traversal; the order in which we visit them does not matter for this application). To perform the traversal write:
public int getSize() {
// Implement local class named Counter here
???
Counter counter = new Counter();
traverse(LEVEL_ORDER, counter);
return counter.getCount();
}
Solution
package edu.lmu.cs.collections;
/**
* A simple interface for binary trees. An empty binary tree is
* represented with the value null; a non-empty tree by its root
* node.
*/
public interface BinaryTreeNode<E>
{
/**
* Returns the data stored in this node.
*/
E getData();
/**
* Modifies the data stored in this node.
*/
void setData(E data);
/**
* Returns the parent of this node, or null if this node is a root.
*/
BinaryTreeNode<E> getParent();
/**
* Returns the left child of this node, or null if it does
* not have one.
*/
BinaryTreeNode<E> getLeft();
/**
* Removes child from its current parent and inserts it as the
* left child of this node. If this node already has a left
* child it is removed.
*
* @exception IllegalArgumentException if the child is
* an ancestor of this node, since that would make
* a cycle in the tree.
*/
void setLeft(BinaryTreeNode<E> child);
/**
* Returns the right child of this node, or null if it does
* not have one.
*/
BinaryTreeNode<E> getRight();
/**
* Removes child from its current parent and inserts it as the
* right child of this node. If this node already has a right
* child it is removed.
* @exception IllegalArgumentException if the child is
* an ancestor of this node, since that would make
* a cycle in the tree.
*/
void setRight(BinaryTreeNode<E> child);
void removeFromParent();
/**
* Visits the nodes in this tree in preorder.
*/
void traversePreorder(Visitor visitor);
void traversePostorder(Visitor visitor);
/**
* Visits the nodes in this tree in inorder.
*/
void traverseInorder(Visitor visitor);
/**
* Simple visitor interface.
*/
public interface Visitor {
<E> void visit(BinaryTreeNode<E> node);
}
}

