Answered step by step
Verified Expert Solution
Question
1 Approved Answer
import java.util.List; import java.util.ArrayList; /** A tree in which each node has an arbitrary number of children. */ public class Tree { private Node root;
import java.util.List; import java.util.ArrayList; /** A tree in which each node has an arbitrary number of children. */ public class Tree { private Node root; class Node { public Object data; public Listchildren; /** Computes the number of leaves of the subtree whose root is this node. @return the number of leaves in the subtree */ public int leafCount() { // ******************************************** // FINISH THIS METHOD // ******************************************** } /** 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); } /** Counts the number of leaves in the tree @return the number of leaves in the tree */ public int leafCount() { if (root == null) { return 0; } else { return root.leafCount(); } } /** 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(); } } }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started