Question

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 {
/**
* Class OurTree has a special node called root, marking the
* beginning of a tree.
*/
Node root;
/**
* Field to capture the total number of nodes in the tree.
*/
int size = 0;
/**
* Class Node is the building block for class Tree. It's an object
* that comprises the data we wish to store (here a String called
* content), and pointers to the left and right child nodes.
*
* +---------------+
* | this node |
* +---------------+
* | content |
* +-------+-------+
* | left | right |
* +-------+-------+
* / \
* / \
* left right
* child child
*/
class Node {
String content;
Node left;
Node right;
/** Basic constructor: add content, leave pointers null */
Node(String s) {
content = s;
left = null;
right = null;
} // constructor Node
} // class Node
/**
* Method to insert a note to tree, using recursion. The method returns a Node
* object, and it has to be called from a node assignment statement, indicating
* the starting point of insertion. Since all insertions begin from root, the
* standard invocation of this recursive method must be:
* root = addRecursively(root, String s)
*
* @param current Node where the insertion begins from (usually, the root)
* @param s Data to insert as a node in the tree.
* @return The top node of the tree, in a successful insertion.
*/
private Node recursiveInsertion(Node current, String s) {
/*
If the current node is empty, "wrap" the data into a node object
and place it here.
*/
if ( current == null ) {
current = new Node(s);
size++;
return current;
}
/*
If the starting node for insertion is not empty, we need to look
if the new data should be placed to the left or the right of the
node. Since we are dealing with Strings, we use the compareTo()
method to determine the relation between the string we are trying to
insert and the value held by the current node.
*/
if (s.compareTo(current.content) < 0) {
current.left = recursiveInsertion(current.left, s);
} else if (s.compareTo(current.content) > 0) {
current.right = recursiveInsertion(current.right, s);
}
/*
If we make it this far, it's because the new data (String s) we are
trying to insert in the tree, already exists and we just found it
as the content of the current node.
*/
return current;
} // method recursiveInsertion
/**
* Wrapper method for the recursive insertion. It starts from the root
* node and lets the recursion take charge until it finds an place for
* the new node containing s. The method, when it executes correctly
* (and it always does) returns the root node of the tree. This may seem
* risky, allowing a method to potentially change the root node. The
* method, however, will always return the root node of the tree.
*
* @param s Data we wish to insert in the tree.
*/
public void addNode(String s) {
root = recursiveInsertion(root,s);
} // method add
/** A quick accessor for the contents of the root node */
public String getRootContent() { return root.content; }
/** A quick accessor for the size of the tree */
public int getSize() { return size; }
public void displayInOrder(Node node) {
if (node==null) {
return;
}
displayInOrder(node.left);
System.out.println(node.content);
displayInOrder(node.right);
}
public void displayInOrder() { displayInOrder(root);}
public static void main(String[] args) {
OurTree sycamore = new OurTree();
sycamore.addNode("m");
sycamore.addNode("k");
sycamore.addNode("t");
sycamore.addNode("r");
sycamore.addNode("b");
sycamore.addNode("f");
sycamore.addNode("z");
sycamore.addNode("g");
//System.out.println(sycamore.getRootContent());
// \System.out.println(sycamore.getSize());
sycamore.displayInOrder();
} // method main
} // class OurTree

Code should start with:

public class BetterTree extends OurTree {
}
0 0
Add a comment Improve this question Transcribed image text
Answer #1

I have changed the structure of tree node in BetterTree. Now, tree nodes of Better tree are having reference to parent nodes as well. So the tree structure looks like this:

Smith Baker Wilson V Able Jones

Updated java code with BetterTree class:

public class OurTree {
/**
* Class OurTree has a special node called root, marking the
* beginning of a tree.
*/
Node root;
/**
* Field to capture the total number of nodes in the tree.
*/
int size = 0;
/**
* Class Node is the building block for class Tree. It's an object
* that comprises the data we wish to store (here a String called
* content), and pointers to the left and right child nodes.
*
* +---------------+
* | this node |
* +---------------+
* | content |
* +-------+-------+
* | left | right |
* +-------+-------+
* / \
* / \
* left right
* child child
*/
class Node {
String content;
Node left;
Node right;
/** Basic constructor: add content, leave pointers null */
Node(String s) {
content = s;
left = null;
right = null;
} // constructor Node
} // class Node
/**
* Method to insert a note to tree, using recursion. The method returns a Node
* object, and it has to be called from a node assignment statement, indicating
* the starting point of insertion. Since all insertions begin from root, the
* standard invocation of this recursive method must be:
* root = addRecursively(root, String s)
*
* @param current Node where the insertion begins from (usually, the root)
* @param s Data to insert as a node in the tree.
* @return The top node of the tree, in a successful insertion.
*/
private Node recursiveInsertion(Node current, String s) {
/*
If the current node is empty, "wrap" the data into a node object
and place it here.
*/
if ( current == null ) {
current = new Node(s);
size++;
return current;
}
/*
If the starting node for insertion is not empty, we need to look
if the new data should be placed to the left or the right of the
node. Since we are dealing with Strings, we use the compareTo()
method to determine the relation between the string we are trying to
insert and the value held by the current node.
*/
if (s.compareTo(current.content) < 0) {
current.left = recursiveInsertion(current.left, s);
} else if (s.compareTo(current.content) > 0) {
current.right = recursiveInsertion(current.right, s);
}
/*
If we make it this far, it's because the new data (String s) we are
trying to insert in the tree, already exists and we just found it
as the content of the current node.
*/
return current;
} // method recursiveInsertion
/**
* Wrapper method for the recursive insertion. It starts from the root
* node and lets the recursion take charge until it finds an place for
* the new node containing s. The method, when it executes correctly
* (and it always does) returns the root node of the tree. This may seem
* risky, allowing a method to potentially change the root node. The
* method, however, will always return the root node of the tree.
*
* @param s Data we wish to insert in the tree.
*/
public void addNode(String s) {
root = recursiveInsertion(root,s);
} // method add
/** A quick accessor for the contents of the root node */
public String getRootContent() { return root.content; }
/** A quick accessor for the size of the tree */
public int getSize() { return size; }
public void displayInOrder(Node node) {
if (node==null) {
return;
}
displayInOrder(node.left);
System.out.println(node.content);
displayInOrder(node.right);
}
public void displayInOrder() { displayInOrder(root);}
public static void main(String[] args) {
BetterTree sycamore = new BetterTree();
sycamore.addNode("m");
sycamore.addNode("k");
sycamore.addNode("t");
sycamore.addNode("r");
sycamore.addNode("b");
sycamore.addNode("f");
sycamore.addNode("z");
sycamore.addNode("g");
//System.out.println(sycamore.getRootContent());
// \System.out.println(sycamore.getSize());
sycamore.displayInOrder(sycamore.root);
} // method main
} // class OurTree

class BetterTree extends OurTree{
NewNode root;
class NewNode extends Node{
public NewNode left = null;
public NewNode right = null;
public NewNode parent;
public NewNode(String s){
super(s);
content = s;
left = null;
right = null;
parent = null;
}
}
//override the recursive method
private NewNode recursiveInsertion(NewNode current, String s) {
/*
If the current node is empty, "wrap" the data into a node object
and place it here.
*/
if ( current == null ) {
current = new NewNode(s);
size++;
return current;
}
/*
If the starting node for insertion is not empty, we need to look
if the new data should be placed to the left or the right of the
node. Since we are dealing with Strings, we use the compareTo()
method to determine the relation between the string we are trying to
insert and the value held by the current node.
*/
if (s.compareTo(current.content) < 0) {
if(current.left==null){
current.left = new NewNode(s);
current.left.parent = current;
return current;
}else current.left = this.recursiveInsertion(current.left, s);
} else if (s.compareTo(current.content) > 0) {
if(current.right==null){
current.right = new NewNode(s);
current.right.parent = current;
return current;
}else current.right = this.recursiveInsertion(current.right, s);
}
/*
If we make it this far, it's because the new data (String s) we are
trying to insert in the tree, already exists and we just found it
as the content of the current node.
*/
return current;
}
public void addNode(String s) {
root = this.recursiveInsertion(root,s);
} // method add
public void displayInOrder(NewNode node) {
if (node==null) {
return;
}
displayInOrder(node.left);
System.out.println(node.content);
displayInOrder(node.right);
}
public int getSize(){
return this.size;
}
}

Add a comment
Know the answer?
Add Answer to:
Instructions Create a class BettterTree that extends OurTree, to facilitate the following. Update: if extending the...
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
  • Question - modify the code below so that for a node, the value of every node...

    Question - modify the code below so that for a node, the value of every node of its right subtree is less the node, and the value of each node of its left subtree is greater than the node. - create such a binary tree in the Main method, and call the following method:  InOrder(Node theRoot),  PreOrder(Node theRoot),  PostOrder(Node theRoot),  FindMin(),  FindMax(),  Find(int key) using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;...

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

  • please make a pretty JAVA GUI for this code this is RED BLACK TREE and i...

    please make a pretty JAVA GUI for this code this is RED BLACK TREE and i Finished code already jus need a JAVA GUI for this code ... if poosible make it pretty to look thanks and please make own GUI code base on my code thanks ex: (GUI only have to show RBTree) ---------------------------------------- RBTree.java import java.util.Stack; public class RBTree{    private Node current;    private Node parent;    private Node grandparent;    private Node header;    private Node...

  • PLEASE HELP! The assignment details are in the *noted part of the code. I REALLY need...

    PLEASE HELP! The assignment details are in the *noted part of the code. I REALLY need help. import java.util.LinkedList; public class TwoDTree { private TwoDTreeNode root; private int size; public TwoDTree() {    clear(); } /** * Returns true if a point is already in the tree. * Returns false otherwise. * * The traversal remains the same. Start at the root, if the tree * is not empty, and compare the x-coordinates of the point passed * in and...

  • 1. Write a function in Tree class which returns true if and only if the tree...

    1. Write a function in Tree class which returns true if and only if the tree satisfies the binary search tree property. The function’s header line is public boolean isValidBST() And in the attached code, you just need to finish the function after the comment: “//Instructor hint: please write your code here:” Make sure you execute your code, and the result in the main function after calling your function should be same as the prompt message I write. Clearly you...

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

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

  • 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 create a class in Java that completes the following conditions MorseTree.java /* This program will...

    Please create a class in Java that completes the following conditions MorseTree.java /* This program will read in letters followed by their morse code * and insert them properly in a tree based on the amount of symbols * it has and whether they are left or right descendent. Finally * it prints a few certain nodes. */ import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class MorseTree {    public static void main(String[] args) throws FileNotFoundException {        //...

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

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