Question

TreeBuilder.java This class is used to create the binary trees for the program. They must be created using a queue-based appr

The class should not have any instance variables and only needs one method. Note that this class does not require a construct

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 as its root.
   * @param element the element that will become the root of the new binary tree
   */
   public LinkedBinaryTree (T dataItem) {
       root = new BinaryTreeNode (dataItem);
   }

   /**
   * Constructor creates a tree from a node storing dataItem as root and two subtrees
   * as left and right subtrees of root.
   * @param dataItem       data to be stored at root node
   * @param leftSubtree   left subtree
   * @param rightSubtree   right subtree
   */

   public LinkedBinaryTree (T dataItem, LinkedBinaryTree leftSubtree,
           LinkedBinaryTree rightSubtree) {
       root = new BinaryTreeNode (dataItem);
       if (leftSubtree != null) root.setLeft(leftSubtree.root);
       else root.setLeft(null);

       if (rightSubtree !=null) root.setRight(rightSubtree.root);
       else root.setRight(null);
   }   

   /**
   * Returns a reference to root node
   * @return a reference to the root node
   */
   public BinaryTreeNode getRoot() {
       return root;
   }   

   /**
   * Returns a reference to the element at the root
   * @return a reference to the specified target
   * @throws EmptyCollectionException if the tree is empty
   */
   public T getDataRoot() throws EmptyCollectionException {
       if (isEmpty()) {
           throw new EmptyCollectionException("Empty tree");
       }
       return root.getData();
   }

   /**
   * Returns true if this binary tree is empty and false otherwise.
   * @return true if this binary tree is empty
   */
   public boolean isEmpty() {
       return root == null;
   }

   /**
   * Returns the integer size of this tree.
   * @return the integer size of this tree
   */
   public int size (BinaryTreeNode r) {
       if (r == null) {
           return 0;
       }

       int tmp = 1;

       if (r.getLeft() != null) {
           tmp += size(r.getLeft());
       }
       if (r.getRight() != null) {
           tmp += size(r.getRight());
       }

       return tmp;
   }

   /**
   * Returns true if the tree with root r contains an element that matches the
   * specified target element and false otherwise.
   * @param r                           root r of a binary tree
   * @param targetElement the element being sought in this tree
   * @return true if the element in is this tree
   * @throws ElementNotFoundException if an element not found exception occurs
   */
   public boolean contains (BinaryTreeNode r, T targetElement) {
       if (r == null) {
           return false;
       }

       if (r.getData().equals(targetElement)) {
           return true;
       } else {

           if (r.getLeft() != null) {
               boolean tmp = contains(r.getLeft(), targetElement);
               if (tmp) {
                   return true;
               }
           }
           if (r.getRight() != null) {
               boolean tmp = contains(r.getRight(), targetElement);
               if (tmp) {
                   return true;
               }
           }

       }

       return false;
   }

   /**
   * Performs an inorder traversal on this binary tree by calling an
   * overloaded, recursive inorder method that starts with
   * the root.
   * @return an in order iterator over this binary tree
   */
   public Iterator iteratorInOrder() {
       ArrayUnorderedList tempList = new ArrayUnorderedList();
       inorder (root, tempList);

       return tempList.iterator();
   }

   /**
   * Performs a recursive inorder traversal.
   * @param node the node to be used as the root for this traversal
   * @param tempList the temporary list for use in this traversal
   */
   protected void inorder (BinaryTreeNode node, ArrayUnorderedList tempList) {
       if (node != null) {
           inorder (node.getLeft(), tempList);
           tempList.addToRear(node.getData());
           inorder (node.getRight(), tempList);
       }
   }

   /**
   * Performs an preorder traversal on this binary tree by calling
   * an overloaded, recursive preorder method that starts with
   * the root.
   * @return an pre order iterator over this tree
   */
   public Iterator iteratorPreOrder() {
       ArrayUnorderedList tempList = new ArrayUnorderedList();
       preorder(root, tempList);

       return tempList.iterator();
   }

   /**
   * Performs a recursive preorder traversal.
   * @param node the node to be used as the root for this traversal
   * @param tempList the temporary list for use in this traversal
   */
   protected void preorder (BinaryTreeNode node, ArrayUnorderedList tempList) {
       if (node != null) {
           tempList.addToRear(node.getData());
           preorder(node.getLeft(), tempList);
           preorder(node.getRight(), tempList);
       }
   }

   /**
   * Performs an postorder traversal on this binary tree by calling
   * an overloaded, recursive postorder method that starts
   * with the root.
   * @return a post order iterator over this tree
   */
   public Iterator iteratorPostOrder() {
       ArrayUnorderedList tempList = new ArrayUnorderedList();
       postorder(root, tempList);

       return tempList.iterator();
   }

   /**
   * Performs a recursive postorder traversal.
   * @param node the node to be used as the root for this traversal
   * @param tempList the temporary list for use in this traversal
   */
   protected void postorder (BinaryTreeNode node, ArrayUnorderedList tempList) {
       if (node != null) {
           postorder(node.getLeft(), tempList);
           postorder(node.getRight(), tempList);
           tempList.addToRear(node.getData());
       }
   }

   /**
   * Performs a levelorder traversal on this binary tree, using a
   * templist.
   * @return a levelorder iterator over this binary tree
   */
   public Iterator iteratorLevelOrder() {
       ArrayUnorderedList tempList = new ArrayUnorderedList();
       LinkedQueue> queue = new LinkedQueue>();
       BinaryTreeNode node = null;

       queue.enqueue(root);

       while (!queue.isEmpty()) {
           node = queue.dequeue();
           tempList.addToRear(node.getData());
           // Add left child.
           if (node.getLeft() != null) {
               queue.enqueue(node.getLeft());
           }
           // Add right child.
           if (node.getRight() != null) {
               queue.enqueue(node.getRight());
           }
       }

       return tempList.iterator();
   }   
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

// TreeBuilder.java

public class TreeBuilder<T> {

   /* method that takes as input an array containing set of values to insert in the new tree's nodes
   * and return the created LinkedBinaryTree object
   */
   public LinkedBinaryTree<T> BuildTree(T array[])
   {
       // create dataQueue to contain all elements of array
       LinkedQueue<T> dataQueue = new LinkedQueue<T>();
       // loop to insert all elements of array in the same order as present in array
       for(int i=0;i<array.length;i++)
       {
           dataQueue.enqueue(array[i]);
       }
      
       // create an empty parentQueue of BinaryNodes
       LinkedQueue<BinaryTreeNode<T>> parentQueue = new LinkedQueue<BinaryTreeNode<T>>();
      
       // create the tree's root node with the first element of dataQueue
       BinaryTreeNode<T> root = new BinaryTreeNode<T>(dataQueue.dequeue());
       parentQueue.enqueue(root); // enqueue root node to parentQueue
      
       // loop till dataQueue is not empty
       while(!dataQueue.isEmpty())
       {
           T a = dataQueue.dequeue(); // dequeue from dataQueue
           T b = dataQueue.dequeue(); // dequeue from dataQueue
          
           // remove the front element from parent
           BinaryTreeNode<T> parent = parentQueue.dequeue();
          
           if(a != null) // if a is not null
           {
               // create a new node with data as a
               BinaryTreeNode<T> node = new BinaryTreeNode<T>(a);
               parent.setLeft(node); // set left child of parent as node
               parentQueue.enqueue(node); // enqueue node to parentQueue
           }
          
           if(b != null) // if b is not null
           {
               // create a new node with data as b
               BinaryTreeNode<T> node = new BinaryTreeNode<T>(b);
               parent.setRight(node); // set right child of parent as node
               parentQueue.enqueue(node); // enqueue node to parentQueue
           }
       }
      
       // return a new Tree with root node as root
       return new LinkedBinaryTree<T>(root);
   }

}

//end of TreeBuilder.java

Add a comment
Know the answer?
Add Answer to:
In Java. How would this method look? LinkedBinaryTree.java import java.util.Iterator; public class LinkedBinaryTree implements BinaryTreeADT {...
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
  • Please I need help ASAP Java Programing: Binary Search Tree Fully implement the BST class in Listing 25.4 (on page 961 of the 11th Edition of the text). Design and write a (main) driver program to com...

    Please I need help ASAP Java Programing: Binary Search Tree Fully implement the BST class in Listing 25.4 (on page 961 of the 11th Edition of the text). Design and write a (main) driver program to completely test every method in the BST class to ensure the class meets all its requirements. You should read the Listing 25.5: TestBST.java for an idea of what your program should look like. Listing 25.4 BST.java public class BST> extends AbstractTree { protected TreeNode...

  • 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...

  • Can you take a look at my code that why the maxDepth function is not working?...

    Can you take a look at my code that why the maxDepth function is not working? public class BinaryTree {          class Node{        int key;        Node left,right;               public Node(int item) {            key = item;            left = right = null;        }    }       Node root;       public void BinaryTree(){        root = null;    }           void...

  • write a new test program called RemoveDuplicates.java. The program reads text input from keyboard or a text file and adds the words to a BST. The program then traverses the BST and prints out the word...

    write a new test program called RemoveDuplicates.java. The program reads text input from keyboard or a text file and adds the words to a BST. The program then traverses the BST and prints out the words in order (based on ASCII/UNICODE order) on the screen (or to output text file). Note that you may need to make some changes to BST.java. Sample test: ----jGRASP exec: java -ea removeDuplicates Original Text: a B 2 n w C q K l 0...

  • Using the following implementation of Tree class Node   {   public int iData;              // data item (key)   public...

    Using the following implementation of Tree class Node   {   public int iData;              // data item (key)   public double dData;           // data item   public Node leftChild;         // this node's left child   public Node rightChild;        // this node's right child   public void displayNode()      // display ourself      {      System.out.print('{');      System.out.print(iData);      System.out.print(", ");      System.out.print(dData);      System.out.print("} ");      }   }  // end class Node //------------------------------------------------------------------ import java.io.IOException; import java.util.Stack; public class Tree { private Node root; // first node of tree // ------------------------------------------------------------- public Tree() // constructor { root = null; }...

  • 1) Extend the Binary Search Tree ADT to include a public method leafCount that returns the...

    1) Extend the Binary Search Tree ADT to include a public method leafCount that returns the number of leaf nodes in the tree. 2) Extend the Binary Search Tree ADT to include a public method singleParent-Count that returns the number of nodes in the tree that have only one child. 3) The Binary search tree ADT is extended to include a boolean method similarTrees that receives references to two binary trees and determines whether the shapes of the trees are...

  • Im having trouble implimenting the addAll method.. import java.util.Collection; public interface Tree<E> extends Collection<E> { /**...

    Im having trouble implimenting the addAll method.. import java.util.Collection; public interface Tree<E> extends Collection<E> { /** Return true if the element is in the tree */ public boolean search(E e); /** Insert element e into the binary tree * Return true if the element is inserted successfully */ public boolean insert(E e); /** Delete the specified element from the tree * Return true if the element is deleted successfully */ public boolean delete(E e);    /** Get the number of...

  • JAVA CODE Topic: BST Animation For each task, submit the source code with detail comments. Objective:...

    JAVA CODE Topic: BST Animation For each task, submit the source code with detail comments. Objective: javafx GUI program for BST Animation. BSTAnimation.java, AbstractTree.java and Tree.java. Modify the BSTAnimation.java  (1) Add Show Preoreder and Show Postorder button. Insert these two buttons next to the Show Inorder button to display tree in selected order. (2) Currently removing node method is to replace the removed node by the highest node on left-subtree. Modify the method by using lowest node on the right-subtree instead....

  • Test Data would be as follows: Using java language. Build an expression tree. • When you...

    Test Data would be as follows: Using java language. Build an expression tree. • When you see a number: o you create a new node with the number as the data. o Then you push the new node to the stack. . When you see a binary operator: 0 You create a new Node for the operator. Then you pop and set the right child. Then you pop and set the left child o Then you push the new node...

  • using java to write,show me the output. please write some common. You CAN NOT use inbuild...

    using java to write,show me the output. please write some common. You CAN NOT use inbuild functions for Tree ADT operations. using code below to finsih public class Main {    public static void main(String[] args) {        BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.right.left = new Node(6); tree.root.right.right = new Node(7); tree.root.left.left.left = new Node(8); tree.root.left.left .right= new Node(9);...

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
ADVERTISEMENT