Question: Java program to count leaves. Use the tree tester and java file provided. public class TreeTester { public static void main(String[] args) { Tree t1
Java program to count leaves. Use the tree tester and java file provided.
public class TreeTester { public static void main(String[] args) { Tree t1 = new Tree("Anne"); Tree t2 = new Tree("Peter"); t1.addSubtree(t2); Tree t3 = new Tree("Zara"); t1.addSubtree(t3); Tree t4 = new Tree("Savannah"); t2.addSubtree(t4); System.out.println("Size: " + t1.size()); System.out.println("Expected: 4"); System.out.println("Leaf count: " + t1.leafCount()); System.out.println("Expected: 2"); } }
Program.
import java.util.List; import java.util.ArrayList; /** A tree in which each node has an arbitrary number of children. Modify the Tree class to add a method that counts the number of leaves in the tree. */ public class Tree { private Node root;
class Node { public Object data; public List
/** Computes the size of the subtree whose root is this node. @return the number of nodes in the subtree */ public int size() { int sum = 0; for (Node child : children) { sum = sum + child.size(); } return 1 + sum; } }
/** Constructs an empty tree. */ public Tree() { root = null; }
/** Constructs a tree with one node and no children. @param rootData the data for the root */ public Tree(Object rootData) { root = new Node(); root.data = rootData; root.children = new ArrayList<>(); }
/** Adds a subtree as the last child of the root. */ public void addSubtree(Tree subtree) { root.children.add(subtree.root); }
/** Computes the size of this tree. @return the number of nodes in the tree */ public int size() { if (root == null) { return 0; } else { return root.size(); } }
public int leafCount() { //Implement the leafCount Method
int sum = 0;
if (children.size() == 0)
{
sum = 1;
}
else
{
for (Node child : children)
{
sum = sum + child.leafCount();
}
}
return sum;
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
