Question

CAN SOMEONE PLEASE SOLVE THIS? THANK YOU.

A leaf node is defined as a node in a tree that has no children. Given a BinarySearchTree write a method for the BST that returns a linked list of all leaves in ascending sorted order. The binary search trees add method adds elements less than the parent to the left and elements greater than the parent to the right. If the tree is empty then an empty list should be returned Suppose the following elements are added to the tree from left to right. [50, 75, 85, 25] The resulting list returned by the method should contain [25, 85] The method should NOT return a linked list of the nodes of the tree but of the elements You are to use the following Java file which contains an implementation for a binary search tree, a main method for testing You may not modify anything pertaining to the add method, the constructor, isEmpty, or the Node class. You may only modify the main method for testing purposes and the method/methods you write except for the header of the getLeafElements method. This means you may not modify the return type, the method name, nor the number of parameters for getLeafElements. You may, however, write additional private helper methods to help you The Java file can be found here: Final Tree.java This problem can be solved recursively without additional data structures (other than those given). To receive full credit, you must implement a recursive method. If your algorithm is purely iterative, you will receive 85% credit.FINALTREE.JAVA:

import java.util.LinkedList;

public class FinalTree<E extends Comparable<? super E>> {

    private Node<E> root;
    private int size;
    
    public FinalTree() {
        root = null;
        size = 0;
    }
    
    public boolean isEmpty() {
        return size == 0;
    }
    
    public void add(E newItem) {
        if (isEmpty()) {
            root = new Node<E>(newItem);
        } else {
            Node<E> parent = null;
            Node<E> temp = root;
            int result = 0;
            while (temp != null) {
                parent = temp;
                result = newItem.compareTo(temp.data);
                if (result < 0) {
                    temp = temp.left;
                } else if (result > 0) {
                    temp = temp.right;
                } else {
                    return;
                }
            }
            if (result < 0) {
                parent.left = new Node<E>(newItem);
            } else if (result > 0) {
                parent.right = new Node<E>(newItem);
            }
        }
        size += 1;
    }
    
    /*****STUDENT CODE HERE*********************************************/
    
    public LinkedList<E> getLeafElements(){
        LinkedList<E> result = new LinkedList<E>();
        /***You may add code here******/
        
        
        
        /*********************************/
        return result;
    }
    
    /*******************************************************************/
    
    
    class Node<T>{
        Node<T> left;
        Node<T> right;
        T data;
        
        public Node(T data) {
            this.data = data;
        }
    }
    
    public static void main(String[] args) {
        FinalTree<String> ft1 = new FinalTree<String>();
        ft1.add("N");
        ft1.add("M");
        ft1.add("Q");
        ft1.add("G");
        ft1.add("H");
        ft1.add("A");
        ft1.add("D");
        ft1.add("T");
        ft1.add("S");
        ft1.add("R");
        ft1.add("P");
        ft1.add("O");
        System.out.println(ft1.getLeafElements()); //Should print [D, H, O, R]
        
        FinalTree<String> ft2 = new FinalTree<String>();
        System.out.println(ft2.getLeafElements()); //Should print []
    }
}
0 0
Add a comment Improve this question Transcribed image text
Answer #1


Given below is the completed code for the question.
To indent code in eclipse , select code by pressing ctrl+a and then indent using ctrl+i
Please do rate the answer if it was helpful. Thank you

import java.util.LinkedList;

public class FinalTree<E extends Comparable<? super E>> {

private Node<E> root;
private int size;
  
public FinalTree() {
root = null;
size = 0;
}
  
public boolean isEmpty() {
return size == 0;
}
  
public void add(E newItem) {
if (isEmpty()) {
root = new Node<E>(newItem);
} else {
Node<E> parent = null;
Node<E> temp = root;
int result = 0;
while (temp != null) {
parent = temp;
result = newItem.compareTo(temp.data);
if (result < 0) {
temp = temp.left;
} else if (result > 0) {
temp = temp.right;
} else {
return;
}
}
if (result < 0) {
parent.left = new Node<E>(newItem);
} else if (result > 0) {
parent.right = new Node<E>(newItem);
}
}
size += 1;
}
  
/*****STUDENT CODE HERE*********************************************/
//helper method
private void getLeafElements(Node n, LinkedList<E> list){
if(n == null)
return;
else{
getLeafElements(n.left, list);
if(n.left == null && n.right == null)
list.add((E)n.data);
getLeafElements(n.right, list);
  
}
}
public LinkedList<E> getLeafElements(){
LinkedList<E> result = new LinkedList<E>();
/***You may add code here******/
getLeafElements(root, result);

/*********************************/
return result;
}
  
/*******************************************************************/
  
  
class Node<T>{
Node<T> left;
Node<T> right;
T data;
  
public Node(T data) {
this.data = data;
}
}
  
public static void main(String[] args) {
FinalTree<String> ft1 = new FinalTree<String>();
ft1.add("N");
ft1.add("M");
ft1.add("Q");
ft1.add("G");
ft1.add("H");
ft1.add("A");
ft1.add("D");
ft1.add("T");
ft1.add("S");
ft1.add("R");
ft1.add("P");
ft1.add("O");
System.out.println(ft1.getLeafElements()); //Should print [D, H, O, R]
  
FinalTree<String> ft2 = new FinalTree<String>();
System.out.println(ft2.getLeafElements()); //Should print []
}
}


output
-----
[D, H, O, R]
[]

Add a comment
Know the answer?
Add Answer to:
CAN SOMEONE PLEASE SOLVE THIS? THANK YOU. FINALTREE.JAVA: import java.util.LinkedList; public class FinalTree<E extends Comparable<? super...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Java help! Please help complete the min method below in bold. import java.util.Arrays; import java.util.ArrayList; import...

    Java help! Please help complete the min method below in bold. import java.util.Arrays; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; /** * Provides an implementation of a binary search tree * with no balance constraints, implemented with linked nodes. * * * */ public class Bst<T extends Comparable<T>> implements Iterable<T> { ////////////////////////////////////////////////////////////////// // I M P L E M E N T T H E M I N M E T H O D B E L O W...

  • BST JAVA FILE import java.util.*; public class BST <E extends Comparable <E>> {    private TreeNode<E>...

    BST JAVA FILE import java.util.*; public class BST <E extends Comparable <E>> {    private TreeNode<E> overallRoot;    public BST() {        overallRoot = null;    }    // ************ ADD ************ //    public void add(E addThis) {        if (overallRoot == null) {            overallRoot = new TreeNode<>(addThis);        } else {            add(overallRoot, addThis);        }    }    private TreeNode<E> add(TreeNode<E> node, E addThis) {        if...

  • Add a non-recursive inorder() method to class LinkedBinaryTree<E> to traverse binary tree. Test inorder() method. Implementation...

    Add a non-recursive inorder() method to class LinkedBinaryTree<E> to traverse binary tree. Test inorder() method. Implementation in Java #########LinkedBinary Tree class######### public class LinkedBinaryTree<E> extends AbstractBinaryTree<E> { //---------------- nested Node class ---------------- /** Nested static class for a binary tree node. */ protected static class Node<E> implements Position<E> { private E element; // an element stored at this node private Node<E> parent; // a reference to the parent node (if any) private Node<E> left; // a reference to the left...

  • In Java. How would this method look? LinkedBinaryTree.java import java.util.Iterator; public class LinkedBinaryTree implements BinaryTreeADT {...

    In Java. How would this method look? LinkedBinaryTree.java import java.util.Iterator; public class LinkedBinaryTree implements BinaryTreeADT {    private BinaryTreeNode root;    /**    * Creates an empty binary tree.    */    public LinkedBinaryTree() {        root = null;    }    /**    * Creates a binary tree from an existing root.    */    public LinkedBinaryTree(BinaryTreeNode root) {        this.root = root;    }    /**    * Creates a binary tree with the specified element...

  • I need help with todo line please public class LinkedList { private Node head; public LinkedList()...

    I need help with todo line please public class LinkedList { private Node head; public LinkedList() { head = null; } public boolean isEmpty() { return head == null; } public int size() { int count = 0; Node current = head; while (current != null) { count++; current = current.getNext(); } return count; } public void add(int data) { Node newNode = new Node(data); newNode.setNext(head); head = newNode; } public void append(int data) { Node newNode = new Node(data);...

  • Instructions Create a class BettterTree that extends OurTree, to facilitate the following. Update: if extending the...

    Instructions Create a class BettterTree that extends OurTree, to facilitate the following. Update: if extending the class is too much, you can modify class OurTree. In our discussions about OurTree, we focused on nodes and their left and right children. For each node in the tree, is there another node of interest in addition to its children? If yes, how would you extend OurTree for that? How will the behavior of addNode method change? OurTree Code: public class OurTree {...

  • P1 is below package p6_linkedList; import java.util.*; public class LinkedList { public Node header; public LinkedList()...

    P1 is below package p6_linkedList; import java.util.*; public class LinkedList { public Node header; public LinkedList() { header = null; } public final Node Search(int key) { Node current = header; while (current != null && current.item != key) { current = current.link; } return current; } public final void Append(int newItem) { Node newNode = new Node(newItem); newNode.link = header; header = newNode; } public final Node Remove() { Node x = header; if (header != null) { header...

  • package hw3; import java.util.LinkedList; /* *********************************************************************** * A simple BST with int keys and no values...

    package hw3; import java.util.LinkedList; /* *********************************************************************** * A simple BST with int keys and no values * * Complete each function below. * Write each function as a separate recursive definition (do not use more than one helper per function). * Depth of root==0. * Height of leaf==0. * Size of empty tree==0. * Height of empty tree=-1. * * TODO: complete the functions in this file. * DO NOT change the Node class. * DO NOT change the name...

  • Java help: Please help complete the locate method that is in bold.. public class LinkedDoubleEndedList implements...

    Java help: Please help complete the locate method that is in bold.. public class LinkedDoubleEndedList implements DoubleEndedList { private Node front; // first node in list private Node rear; // last node in list private int size; // number of elements in list ////////////////////////////////////////////////// // YOU MUST IMPLEMENT THE LOCATE METHOD BELOW // ////////////////////////////////////////////////// /** * Returns the position of the node containing the given value, where * the front node is at position zero and the rear node is...

  • Q1) Write a method called inToTree of ExpressionTree class which takes a string of infix expression...

    Q1) Write a method called inToTree of ExpressionTree class which takes a string of infix expression (fully parenthesized), resets the root of the expression tree to such tree which constructed from the expression. The root set to null of the expression contains characters other than value, operator, and parenthesis or if it’s not an in-fix full parenthesized expression. You may assume each value is single digit only . public void inToTree(String expression){ You may use a JCF Deque class as...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT