Please help with this code Add a method int getSize to Binar
Please help with this code.
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 named Counter which implements the BinaryTree Visitor<E> interface:
Here is the BinaryTreeNode.java code to modify/edit:
public interface BinaryTreeNode<E>
{
E getData();
void setData(E data);
BinaryTreeNode<E> getParent();
BinaryTreeNode<E> getLeft();
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);
}
}
Solution
//Here the implementation of getSize() method in which local class Counter is implemented.
//Add this method to your BinaryTree.java file.
//There is no need make changes in BinaryTreeNode class file.
//Since BinaryTreeNode is implemented by BinaryTree.
public int getSize()
{
class Counter implements BinaryTreeVisitor<E>
{
int count;
Counter()
{
count=0;
}
int getCount()
{
return count;
}
void visit(E e)
{
count++;
}
}
Counter counter=new Counter();
//Here root is head node in tree
//You must need to maintain root node in BinaryTree class.
traverse(root,counter); //Calls the traverse method which visit each node in tree.
return counter.getCount();
}
//Here the implemetation of inorder traversal for your reference.
void traverse(BinaryTreeNode<E> root,Counter counter)
{
if(root == null)
return;
Stack<BinaryTreeNode<E>> stack = new Stack<BinaryTreeNode>();
//define a pointer to track nodes
BinaryTreeNode<E> p = root;
while(!stack.empty() || p != null){
// if it is not null, push to stack
//and go down the tree to left
if(p != null){
stack.push(p);
p = p.left;
// if no left child
// pop stack, process the node
// then let p point to the right
}else{
BinaryTreeNode<E> t = stack.pop();
//lst.add(t.val);
counter.visit(t); //Visit the node in a tree by calling visit method of Counter local class
p = t.right;
}
}
}


