Question: Program to count leaves. Use the tree tester. public class TreeTester { public static void main(String[] args) { Tree t1 = new Tree(Anne); Tree t2
Program to count leaves. Use the tree tester.
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"); } }
My program is below but i have errors. Please help to rectify. Thanks
import java.util.List;
import java.util.ArrayList;
/**
add a method that counts the number of leaves in the tree. The error is at leafcount
*/
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()
{
int sum = 0;
if (children.size() == 0)
{
sum = 1;
}
else
{
for (Node child : children)
{
sum = sum + child.leafCount();
}
}
return sum;
public static int leafCount(Node child)
{
//Implement the leafCount Method
if (child == null)
return 0;
if (child.left==null) and (child.right==null)
return 1;
else
return leafCount(n.left)+leafCount(n.right);
}
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
