Question

V testANodeSimpleGetChildrenBasic V testANodeSimpl

Does not pass the testcase testDTreeAdvancedReRootchangesParent

Java

I'm trying to extend the implementation of a general tree with new operations that change the structure of the tree.

I've created 5 classes: Node.java, SimpleNode.java, Tree.java, RerootableTree.java and SimpleTree.java(which is the main java class that I need to change).

The code does not pass ONE TESTCASE : testDTreeAdvancedReRootchangesParent

The code passes all the other testcases except theone mentioned above. This is because in the SimpleTree.java the method "reRoot(Node newRoot)" is most likely incorrect, this is why it doesnt run. Can you solve the public void reRoot(Node newRoot) in SimpleTree.java class

These are the 5 classes:

Node.java (Does not need change):

import java.util.List;

public interface Node {
  
   /**
   * Recovers the value stored in the node
   * @return the object stored in the node
   */
   public Object getElement();

   /**
   * Sets the value stored in the node
   * @param element the value to store in the node
   */
   public void setElement(Object element);

   /**
   * Recover the parent stored of the current node
   * @return the parent of the current node
   */
   public Node getParent();

   /**
   * Set the parent of the current node
   * @param parent to set for the current node
   */
   public void setParent(Node parent);

   /**
   * Recover a list of children in order from left to right for the node
   * @return a list of children for the node
   */
   public List getChildren();

   /**
   * Append a child node to the list of children in the order from left to right
   * @param child the new node to add to the list of children
   */  
   public void addChild(Node child);

   /**
   * Remove a child node from the list of children
   * @param child the new node to remove from the list of children
   */      
   public void removeChild(Node child);

   /**
   * Check if the node is a leaf node. A leaf node is a node which has no children
   * @return true if a leaf node else false
   */
   public boolean isLeafNode();
  
   /**
   * Check if the node is a root node. A root node is a node which does not have a parent
   * @return true if a root node else false
   */
   public boolean isRootNode();  
}

************************************************************************************************************************************************

SimpleNode.java:

import java.util.ArrayList;
import java.util.List;
////////////////////////////////////
// your code in this class 1 of 2 //
////////////////////////////////////
public class SimpleNode implements Node {
// implement 3 private classes by introducing 1. element, 2. parent and
// 3.children.
private Object element;
private Node parent;
private List children;
// implement and add all the public classes in the
// Node.java file with it's return value
// Recovers the value stored in the node
// return the object stored in the node
public Object getElement() {
return this.element;
}
// Sets the value stored in the node
// param element the value to store in the node
public void setElement(Object element) {
this.element = element;
}
// Recover the parent stored of the current node
// return the parent of the current node
public Node getParent() {
return this.parent;
}
// Set the parent of the current node
// param parent to set for the current node
public void setParent(Node parent) {
this.parent = parent;
}
// Recover a list of children in order from left to right for the node
// @return a list of children for the node
public List getChildren() {
return this.children;
}
// Append a child node to the list of children in the order from left to
// right
// @param child the new node to add to the list of children
public void addChild(Node child) {
this.children.add(child);
child.setParent(this);
}
// Remove a child node from the list of children
// @param child the new node to remove from the list of children
public void removeChild(Node child) {
this.children.remove(child);
}
// Check if the node is a leaf node. A leaf node is a node which has no
// children
// @return true if a leaf node else false
public boolean isLeafNode() {
return children.isEmpty();
}
// Check if the node is a root node. A root node is a node which does not
// have a parent
// @return true if a root node else false
public boolean isRootNode() {
return parent == null;
}
// and finally add in the last step a SimpleNode() class
public SimpleNode() {
this.parent = null;
this.children = new ArrayList();
}
}

*********************************************************************************************************************************************

Tree.java:

public interface Tree {
  
   /**
   * Calculates the size of the tree.
   * @return the number of internal and leaf nodes in the tree
   */
   public int size();

   /**
   * Checks if the tree is empty
   * @return true if the tree contains no nodes else false
   */
   public boolean isEmpty();

   /**
   * Computes the maximum height of the tree
   * @return the maximum height of the tree
   */  
   public int getHeight();
  
   /**
   * Adds a node as the root of the tree
   * @param root add a node as the root of the tree
   */
   public void setRoot(Node root);

   /**
   * Recovers the root of the tree
   * @return the root node of the tree
   */
   public Node getRoot();
  
   /**
   * Recovers the distance between the root node and the query node.
   * The distance is in terms of the number of edges between the query node
   * and the root.
    * returns a value less than zero if root or node is null
   * @param node is the initial location of the query
   * @return the distance from node to the root
   */
   public int distanceToRoot(Node node);
  
}

***************************************************************************************************************************************

SimpleTree.java:

public class SimpleTree implements RerootableTree {
// Implement a private class by introducing the root.
private Node root;
// Now
// implement and add all the public classes in the
// Tree.java file with it's return value
// Calculates the size of the tree.
// @return the number of internal and leaf nodes in the tree
public int size() {
return this.size(this.root);
}
private int size(Node root) {
// base case
if (root == null) {
return 0;
}
// recurse
int total = 1;
for (Node n : root.getChildren()) {
total += this.size(n);
}
return total;
}
/**
* Checks if the tree is empty
*
* @return true if the tree contains no nodes else false
*/
public boolean isEmpty() {
return this.root == null;
}
/**
* Computes the maximum height of the tree
*
* @return the maximum height of the tree
*/
// gets the height from the private method of get height.
public int getHeight() {
return this.getHeight(root);
}// Computes the maximum height of the tree
private int getHeight(Node root) {
int h = 0;
// Base case: If tree is empty then height is -1.
if (root == null) {
return -1;
}
// Recurse through and add 1 every time method has to recurse again
else {
for (Node n : root.getChildren()) {
h = Math.max(h, 1 + getHeight(n));
}
}
return h;
}
/**
* Adds a node as the root of the tree
*
* @param root
* add a node as the root of the tree
*/
public void setRoot(Node root) {
this.root = root;
}
/**
* Recovers the root of the tree
*
* @return the root node of the tree
*/
public Node getRoot() {
return this.root;
}
/**
* Recovers the distance between the root node and the query node. The
* distance is in terms of the number of edges between the query node and
* the root. returns a value less than zero if root or node is null
*
* @param node
* is the initial location of the query
* @return the distance from node to the root
*/
public int distanceToRoot(Node node) {
// Base case
if (node == getRoot())
return 0;
// We recurse through the tree add 1 every time method has to recurse
// again
else
return 1 + distanceToRoot(node.getParent());
}
// Now implementing the classes from RerootableTree.java
/**
* Sets a new root node for the current tree. To see how this operation
* works check the assignment specifications
*
* @param newRoot
* the node which will be updated as the root for the current
* tree
*/
public void reRoot(Node newRoot) {
  
// Check if newRoot has a parent and has been added to the tree or its just isolated node
if(newRoot.getParent()!=null)
{
Node parentOfNewRoot = newRoot.getParent();
// Base case: While the tree is empty or the root already equals new
// root then exit the method
if (isEmpty() == true || this.getRoot().equals(newRoot)) {
return;
} else {
// We recurse through the tree
this.reRoot(parentOfNewRoot);
// Setting the root to the root entered as parameter as this will be
// the new root
this.setRoot(newRoot);
// Make sure that new root is not a child anymore of the parents it
// had previously, by removing it
parentOfNewRoot.removeChild(newRoot);
// The parents of the new root will now become its children
newRoot.addChild(parentOfNewRoot);
}
}
}
/**
* Checks if the current tree is a clone of "tree". For more details see
* assignment specifications
*
* @param tree
* @return true if the tree is a clone otherwise false
*/
public boolean isClone(Tree tree) {
// While both tree are empty we return true as they will be equal
if (tree.isEmpty() == true && this.isEmpty() == true) {
return true;
}
// If the size of both tree is not equal then they cannot be equal
if (!(this.size() == tree.size())) {
return false;
}
// If the root of both tree is not equal then they cannot be equal
if (!(this.getRoot() == tree.getRoot())) {
return false;
}
// If the number of children of both tree is not equal then they cannot
// be equal
if (this.getRoot().getChildren().size() != tree.getRoot().getChildren().size()) {
return false;
}
// We create two new trees
SimpleTree a = new SimpleTree();
SimpleTree b = new SimpleTree();
// If the tree pass all the above conditions then we iterate through the
// tree checking each node
for (int i = 0; i < a.size(); i++) {
Node a1 = a.getRoot().getChildren().get(i);
Node b1 = b.getRoot().getChildren().get(i);
a.setRoot(a1);
b.setRoot(b1);
// Comparing the tree by setting each child as the root node. If
// trees are not equal return false.
if (a.isClone(b) == false)
return false;
}
// If both trees are not empty and all conditions fail the return true
// as this means both tree are equal
return true;
}
// Finally implement the whole data
public SimpleTree() {
this.root = null;
}

  
}

************************************************************************************************************************************************

RerootableTree.java:

public interface RerootableTree extends Tree {
  
   /**
   * Sets a new root node for the current tree. To see how this operation works
   * check the assignment specifications
   * @param newRoot the node which will be updated as the root for the current tree
   */
   public void reRoot(Node newRoot) ;

   /**
   * Checks if the current tree is a clone of "tree". For more details see assignment specifications
   * @param tree
   * @return true if the tree is a clone otherwise false
   */
   public boolean isClone(Tree tree) ;
}

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

PROGRAM CODE:

RerootableTree.java

public interface RerootableTree extends Tree {
  
   /**
   * Sets a new root node for the current tree. To see how this operation works
   * check the assignment specifications
   * @param newRoot the node which will be updated as the root for the current tree
   */
   public Node reRoot(Node newRoot) ;
   /**
   * Checks if the current tree is a clone of "tree". For more details see assignment specifications
   * @param tree
   * @return true if the tree is a clone otherwise false
   */
   public boolean isClone(Tree tree) ;
   }

SimpleTree.java

import java.util.List;

public class SimpleTree implements RerootableTree {
   // Implement a private class by introducing the root.
   private Node root;
   // Now
   // implement and add all the public classes in the
   // Tree.java file with it's return value
   // Calculates the size of the tree.
   // @return the number of internal and leaf nodes in the tree
   public int size() {
   return this.size(this.root);
   }
   private int size(Node root) {
   // base case
   if (root == null) {
   return 0;
   }
   // recurse
   int total = 1;
  
   for (Node n : root.getChildren()) {
   total += this.size(n);
   }
   return total;
   }
   /**
   * Checks if the tree is empty
   *
   * @return true if the tree contains no nodes else false
   */
   public boolean isEmpty() {
   return this.root == null;
   }
   /**
   * Computes the maximum height of the tree
   *
   * @return the maximum height of the tree
   */
   // gets the height from the private method of get height.
   public int getHeight() {
   return this.getHeight(root);
   }// Computes the maximum height of the tree
   private int getHeight(Node root) {
   int h = 0;
   // Base case: If tree is empty then height is -1.
   if (root == null) {
   return -1;
   }
   // Recurse through and add 1 every time method has to recurse again
   else {
       List<Node> nodes = root.getChildren();
   for (Node n : nodes) {
   h = Math.max(h, 1 + getHeight(n));
   }
   }
   return h;
   }
   /**
   * Adds a node as the root of the tree
   *
   * @param root
   * add a node as the root of the tree
   */
   public void setRoot(Node root) {
   this.root = root;
   }
   /**
   * Recovers the root of the tree
   *
   * @return the root node of the tree
   */
   public Node getRoot() {
   return this.root;
   }
   /**
   * Recovers the distance between the root node and the query node. The
   * distance is in terms of the number of edges between the query node and
   * the root. returns a value less than zero if root or node is null
   *
   * @param node
   * is the initial location of the query
   * @return the distance from node to the root
   */
   public int distanceToRoot(Node node) {
   // Base case
   if (node == getRoot())
   return 0;
   // We recurse through the tree add 1 every time method has to recurse
   // again
   else
   return 1 + distanceToRoot(node.getParent());
   }
   // Now implementing the classes from RerootableTree.java
   /**
   * Sets a new root node for the current tree. To see how this operation
   * works check the assignment specifications
   *
   * @param newRoot
   * the node which will be updated as the root for the current
   * tree
   */
   public Node reRoot(Node newRoot) {
  
   // Check if newRoot has a parent and has been added to the tree or its just isolated node
   if(newRoot.getParent()!=null)
   {
   Node parentOfNewRoot = newRoot.getParent();
   // Base case: While the tree is empty or the root already equals new
   // root then exit the method
   if (isEmpty() == true || this.getRoot().equals(newRoot)) {
   return newRoot;
   } else {
   // We recurse through the tree
   this.reRoot(parentOfNewRoot);
   // Setting the root to the root entered as parameter as this will be
   // the new root
   this.setRoot(newRoot);
   // Make sure that new root is not a child anymore of the parents it
   // had previously, by removing it
   parentOfNewRoot.removeChild(newRoot);
   // The parents of the new root will now become its children
   newRoot.addChild(parentOfNewRoot);
   }
   }
   return newRoot;
   }
   /**
   * Checks if the current tree is a clone of "tree". For more details see
   * assignment specifications
   *
   * @param tree
   * @return true if the tree is a clone otherwise false
   */
   public boolean isClone(Tree tree) {
   // While both tree are empty we return true as they will be equal
   if (tree.isEmpty() == true && this.isEmpty() == true) {
   return true;
   }
   // If the size of both tree is not equal then they cannot be equal
   if (!(this.size() == tree.size())) {
   return false;
   }
   // If the root of both tree is not equal then they cannot be equal
   if (!(this.getRoot() == tree.getRoot())) {
   return false;
   }
   // If the number of children of both tree is not equal then they cannot
   // be equal
   if (this.getRoot().getChildren().size() != tree.getRoot().getChildren().size()) {
   return false;
   }
   // We create two new trees
   SimpleTree a = new SimpleTree();
   SimpleTree b = new SimpleTree();
   // If the tree pass all the above conditions then we iterate through the
   // tree checking each node
   for (int i = 0; i < a.size(); i++) {
   Node a1 = a.getRoot().getChildren().get(i);
   Node b1 = b.getRoot().getChildren().get(i);
   a.setRoot(a1);
   b.setRoot(b1);
   // Comparing the tree by setting each child as the root node. If
   // trees are not equal return false.
   if (a.isClone(b) == false)
   return false;
   }
   // If both trees are not empty and all conditions fail the return true
   // as this means both tree are equal
   return true;
   }
   // Finally implement the whole data
   public SimpleTree() {
   this.root = null;
   }
  
   }

//Main class created by me to test

MainClass.java

public class MainClass {

   /**
   * @param args
   */
   public static void main(String[] args) {
       Node node = new SimpleNode();
       Node node1 = new SimpleNode();
       node.setElement("Child");
       node1.setElement("Parent");
       node.addChild(node1);
       SimpleTree tree = new SimpleTree();
       tree.setRoot(node);
       System.out.println(tree.getRoot().getElement());
       tree.setRoot(tree.reRoot(node1));
       System.out.println(tree.getRoot().getElement());
       System.out.println(tree.size());
   }

}

OUTPUT:

Child //output before rerooting
Parent //output after rerooting
2

Add a comment
Know the answer?
Add Answer to:
Does not pass the testcase testDTreeAdvancedReRootchangesParent Java I'm trying to extend the implementation of a general...
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
  • 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; }...

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

  • Need help in the below question. Answer in java Start with the tree.java program (Listing 8.1)...

    Need help in the below question. Answer in java Start with the tree.java program (Listing 8.1) and modify it to create a binary tree from a string of letters (like A, B, and so on) entered by the user. Each letter will be displayed in its own node. Construct the tree so that all the nodes that contain letters are leaves. Parent nodes can contain some non-letter symbol like +. Make sure that every parent node has exactly two children....

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

  • Need help with these two questions String outputBreadthFirstSearch(): returns a string represenng a breadth first traversal....

    Need help with these two questions String outputBreadthFirstSearch(): returns a string represenng a breadth first traversal. So, for example, for the tree shown in Figure 1, the method should output the string "bcaahttaetersse" 4. String outputDepthFirstSearch(): returns a string represenng a pre order depth first traversal. So, for example, for the tree shown in Figure 1, the method should output the string "batcathateersse This is my code so far public class Trie { final TrieNode root; public Trie() { this.root...

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

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

  • Since we do not want to have to rewrite this code when the element type changes,...

    Since we do not want to have to rewrite this code when the element type changes, this classes uses a Comparator to assist in ordering the elements. You will need to complete the siftUpComparator() and siftDownComparator() methods in the LinkedHeap Class. siftUp §Added element may violate heap-order property §siftUp() restores order starting at added node §Processing will continue working up the tree until: úFinds properly ordered node & parent úReaches the root (reaches node without parent) siftDown §Restores heap’s order...

  • Removing Nodes from a Binary Tree in Java This section requires you to complete the following...

    Removing Nodes from a Binary Tree in Java This section requires you to complete the following method within BinaryTree.java: public void remove(K key) { } The remove method should remove the key from the binary tree and modify the tree accordingly to maintain the Binary Search Tree Principle. If the key does not exist in the binary tree, no nodes should be removed. In case there is a non-null left child, it should take the place of the removed node....

  • Preliminaries Download the template class and the driver file. Objective Learn how to traverse a binary...

    Preliminaries Download the template class and the driver file. Objective Learn how to traverse a binary search tree in order. Description For the template class BinarySearchTree, fill in the following methods: insert - Inserts values greater than the parent to the right, and values lesser than the parent to the left.parameters elem - The new element to be inserted into the tree. printInOrder - Prints the values stored in the tree in ascending order. Hint: Use a recursive method to...

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