Question: JAVA FINDING ALL LEAF NODE OUT FROM A ROOTED TREE public class TreeNode < E > { public E element ; public TreeNode < E

JAVA FINDING ALL LEAF NODE OUT FROM A ROOTED TREE public class TreeNode<E> { public E element; public TreeNode<E> parent; public List<TreeNode<E>> children; public TreeNode(E element, TreeNode<E> parent) { this.element = element; children = new ArrayList<TreeNode<E>>(); } public TreeNode(E element) { this(element, null); } public void addChild(TreeNode<E> node) { this.children.add(node); node.parent = this; } public String toString() { return element.toString(); } }
 public class RootedTree { private final String PADDING_STRING = "0-"; public TreeNode<String> root = null; public RootedTree(TreeNode<String> node) { this(); root = node; node.parent = null; } public RootedTree(String filename) throws IOException { this(); load(filename); } public RootedTree() { } public void save(String filename) throws IOException { LineWriter writer = new LineWriter(); writer.open(filename); recursiveSave(writer, "", root); writer.close(); } private void recursiveSave(LineWriter writer, String padding, TreeNode<String> current) { if(current != null) { writer.println(padding + current.element.toString()); for(TreeNode<String> child : current.children) { recursiveSave(writer, padding + PADDING_STRING, child); } } } public void load(String filename) throws IOException { LineReader reader = new LineReader(); reader.open(filename); root = new TreeNode<String>(reader.next()); loadRecursively(reader, root, 0); reader.close(); } private void loadRecursively(LineReader reader, TreeNode<String> current, int level) throws IOException { while(reader.hasNext()) { String line = reader.peek(); String[] split = line.split(PADDING_STRING); int newLevel = split.length - 1; String newString = split[newLevel]; if(newLevel > level + 1 || newLevel <= 0) { throw new IOException("Invalid data format."); } else if(newLevel == level + 1) { TreeNode<String> node = new TreeNode<String>(newString); current.addChild(node); reader.next(); loadRecursively(reader, node, newLevel); } else { return; } } }
 // Problem 2 (15 pts): Fill in the getLeafNodes method. This method should return // a list consisting of all of the leaf nodes in the rooted tree. // Note: You are allowed to add helper methods and use recursion. public List<TreeNode<String>> getLeafNodes(){ return null; }

I need help with question #2 Thanks in advance!

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!