Using the attached files, TreeAssignment.java and IntTree.java Add to the methods in IntTree so that the sumNodes methods returns the sum of all the integers in the tree. countLeftNodes should count up all the left children in the tree.
Provided in IntTree.java is an example to help you called countEvenBranches which counts all the branches (nodes with children) with even values, but not leaves (nodes with no children) with even values.
Both methods return an integer. The tree generated is random so each run will be slightly different.
TreeAssignment.java
public class TreeAssignment {
// DO NOT CHANGE LINES IN MAIN- YOU MAY ADD AT BOTTOM
BUT NOT REMOVE ANY LINES
public static void main(String[] args) {
// create int tree with 10 random elements
// you may make this smaller for
testing
IntTree theTree = new IntTree(3);
// print the tree
theTree.printStructure();
// call already developed routine to count even branches -
this
// counts branches with even nodes, not even leaf nodes
int evenCount = theTree.countEvenBranches();
System.out.println("There are " + evenCount + " even
branches");
// call user developed routine to
count left Nodes
int leftNodes = theTree.countLeftNodes();
System.out.println("The number of left nodes is " +
leftNodes);
// call second user developmed routine to sum the values of all the
integers in the tree
int totalSum = theTree.sumNodes();
System.out.println("The total sum is " + totalSum);
}
}
public class IntTree
{ //we need to give refrence to the methods.Assuming theTree is root node and is global.
public int sumNodes(IntTree theTree)
{ if(theTree==NULL)
return 0;
return(theTree.key + (theTree.left) + (theTree.right);
}
public int countLeftNodes(IntTree theTree)
{
int count = 0;
if(theTree.left!=NULL)
count=count+1+countLeftNodes(theTree.left);
if(theTree.right ! =NULL)
count=count+1+countLeftNodes(theTree.right);
retrun count;
}
public int countEvenNodes(IntTree theTree)
{ if(theTree == NULL)
return 0;
else
{
int count = 0;
if((theTree.left != NULL || theTree.right !=NULL) && theTree.data%2==0)
count=count+1+countEvenNodes(theTree.left)+countEvenNodes(theTree.right);
return count;
}
}
Get Answers For Free
Most questions answered within 1 hours.