Question

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 the same. (The nodes do not have to contain the same values, but each node must have the same number of children)
A) Write the declaration of the function similarTrees method. Include adequate comments.
B) Write the body of the function similarTrees method.

(Can you write the code using the JAVA language and also put the code to copy for each question? Thank you.)


Below, I also have attached the BinarySearchTree, the Interface File and BSTNode file. (the code is from the text)
BinarySearchTree
:
//----------------------------------------------------------------------------
// BinarySearchTree.java by Dale/Joyce/Weems Chapter 8
//
// Defines all constructs for a reference-based BST
//----------------------------------------------------------------------------

package ch08.trees;
import ch05.queues.*;
import ch03.stacks.*;
import support.BSTNode;
public class BinarySearchTree>
implements BSTInterface
{
protected BSTNode root; // reference to the root of this BST
boolean found; // used by remove

// for traversals
protected LinkedUnbndQueue inOrderQueue; // queue of info
protected LinkedUnbndQueue preOrderQueue; // queue of info
protected LinkedUnbndQueue postOrderQueue; // queue of info
public BinarySearchTree()
// Creates an empty BST object.
{
root = null;
}
public boolean isEmpty()
// Returns true if this BST is empty; otherwise, returns false.
{
return (root == null);
}
private int recSize(BSTNode tree)
// Returns the number of elements in tree.
{
if (tree == null)
return 0;
else
return recSize(tree.getLeft()) + recSize(tree.getRight()) + 1;
}
public int size()
// Returns the number of elements in this BST.
{
return recSize(root);
}
public int size2()
// Returns the number of elements in this BST.
{
int count = 0;
if (root != null)
{
LinkedStack> hold = new LinkedStack>();
BSTNode currNode;
hold.push(root);
while (!hold.isEmpty())
{
currNode = hold.top();
hold.pop();
count++;
if (currNode.getLeft() != null)
hold.push(currNode.getLeft());
if (currNode.getRight() != null)
hold.push(currNode.getRight());
}
}
return count;
}
private boolean recContains(T element, BSTNode tree)
// Returns true if tree contains an element e such that
// e.compareTo(element) == 0; otherwise, returns false.
{
if (tree == null)
return false; // element is not found
else if (element.compareTo(tree.getInfo()) < 0)
return recContains(element, tree.getLeft()); // Search left subtree
else if (element.compareTo(tree.getInfo()) > 0)
return recContains(element, tree.getRight()); // Search right subtree
else
return true; // element is found
}
public boolean contains (T element)
// Returns true if this BST contains an element e such that
// e.compareTo(element) == 0; otherwise, returns false.
{
return recContains(element, root);
}

private T recGet(T element, BSTNode tree)
// Returns an element e from tree such that e.compareTo(element) == 0;
// if no such element exists, returns null.
{
if (tree == null)
return null; // element is not found
else if (element.compareTo(tree.getInfo()) < 0)
return recGet(element, tree.getLeft()); // get from left subtree
else
if (element.compareTo(tree.getInfo()) > 0)
return recGet(element, tree.getRight()); // get from right subtree
else
return tree.getInfo(); // element is found
}
public T get(T element)
// Returns an element e from this BST such that e.compareTo(element) == 0;
// if no such element exists, returns null.
{
return recGet(element, root);
}
private BSTNode recAdd(T element, BSTNode tree)
// Adds element to tree; tree retains its BST property.
{
if (tree == null)
// Addition place found
tree = new BSTNode(element);
else if (element.compareTo(tree.getInfo()) <= 0)
tree.setLeft(recAdd(element, tree.getLeft())); // Add in left subtree
else
tree.setRight(recAdd(element, tree.getRight())); // Add in right subtree
return tree;
}
public void add (T element)
// Adds element to this BST. The tree retains its BST property.
{
root = recAdd(element, root);
}
private T getPredecessor(BSTNode tree)
// Returns the information held in the rightmost node in tree
{
while (tree.getRight() != null)
tree = tree.getRight();
return tree.getInfo();
}
private BSTNode removeNode(BSTNode tree)
// Removes the information at the node referenced by tree.
// The user's data in the node referenced by tree is no
// longer in the tree. If tree is a leaf node or has only
// a non-null child pointer, the node pointed to by tree is
// removed; otherwise, the user's data is replaced by its
// logical predecessor and the predecessor's node is removed.
{
T data;
if (tree.getLeft() == null)
return tree.getRight();
else if (tree.getRight() == null)
return tree.getLeft();
else
{
data = getPredecessor(tree.getLeft());
tree.setInfo(data);
tree.setLeft(recRemove(data, tree.getLeft()));
return tree;
}
}
private BSTNode recRemove(T element, BSTNode tree)
// Removes an element e from tree such that e.compareTo(element) == 0
// and returns true; if no such element exists, returns false.
{
if (tree == null)
found = false;
else if (element.compareTo(tree.getInfo()) < 0)
tree.setLeft(recRemove(element, tree.getLeft()));
else if (element.compareTo(tree.getInfo()) > 0)
tree.setRight(recRemove(element, tree.getRight()));
else
{
tree = removeNode(tree);
found = true;
}
return tree;
}
public boolean remove (T element)
// Removes an element e from this BST such that e.compareTo(element) == 0
// and returns true; if no such element exists, returns false.
{
root = recRemove(element, root);
return found;
}
private void inOrder(BSTNode tree)
// Initializes inOrderQueue with tree elements in inOrder order.
{
if (tree != null)
{
inOrder(tree.getLeft());
inOrderQueue.enqueue(tree.getInfo());
inOrder(tree.getRight());
}
}
private void preOrder(BSTNode tree)
// Initializes preOrderQueue with tree elements in preOrder order.
{
if (tree != null)
{
preOrderQueue.enqueue(tree.getInfo());
preOrder(tree.getLeft());
preOrder(tree.getRight());
}
}
private void postOrder(BSTNode tree)
// Initializes postOrderQueue with tree elements in postOrder order.
{
if (tree != null)
{
postOrder(tree.getLeft());
postOrder(tree.getRight());
postOrderQueue.enqueue(tree.getInfo());
}
}
public int reset(int orderType)
// Initializes current position for an iteration through this BST
// in orderType order. Returns current number of nodes in the BST.
{
int numNodes = size();
if (orderType == INORDER)
{
inOrderQueue = new LinkedUnbndQueue();
inOrder(root);
}
else
if (orderType == PREORDER)
{
preOrderQueue = new LinkedUnbndQueue();
preOrder(root);
}
if (orderType == POSTORDER)
{
postOrderQueue = new LinkedUnbndQueue();
postOrder(root);
}
return numNodes;
}
public T getNext (int orderType)
// Preconditions: The BST is not empty
// The BST has been reset for orderType
// The BST has not been modified since the most recent reset
// The end of orderType iteration has not been reached
//
// Returns the element at the current position on this BST for orderType
// and advances the value of the current position based on the orderType.
{
if (orderType == INORDER)
return inOrderQueue.dequeue();
else
if (orderType == PREORDER)
return preOrderQueue.dequeue();
else
if (orderType == POSTORDER)
return postOrderQueue.dequeue();
else return null;
}
}
BSTInterface:
//----------------------------------------------------------------------------
// BSTInterface.java by Dale/Joyce/Weems Chapter 8
//
// Interface for a class that implements a binary search tree (BST).
//
// The trees are unbounded and allow duplicate elements, but do not allow null
// elements. As a general precondition, null elements are not passed as
// arguments to any of the methods.
//
// The tree supports iteration through its elements in INORDER, PREORDER,
// and POSTORDER.
//----------------------------------------------------------------------------
package ch08.trees;
public interface BSTInterface>
{
// used to specify traversal order
static final int INORDER = 1;
static final int PREORDER = 2;
static final int POSTORDER = 3;
boolean isEmpty();
// Returns true if this BST is empty; otherwise, returns false.

int size();
// Returns the number of elements in this BST.
boolean contains (T element);
// Returns true if this BST contains an element e such that
// e.compareTo(element) == 0; otherwise, returns false.

boolean remove (T element);
// Removes an element e from this BST such that e.compareTo(element) == 0
// and returns true; if no such element exists, returns false.

T get(T element);
// Returns an element e from this BST such that e.compareTo(element) == 0;
// if no such element exists, returns null.
void add (T element);
// Adds element to this BST. The tree retains its BST property.

int reset(int orderType);
// Initializes current position for an iteration through this BST
// in orderType order. Returns current number of nodes in the BST.
T getNext (int orderType);
// Preconditions: The BST is not empty
// The BST has been reset for orderType
// The BST has not been modified since the most recent reset
// The end of orderType iteration has not been reached
//
// Returns the element at the current position on this BST for orderType
// and advances the value of the current position based on the orderType.
}

media%2F6b1%2F6b141637-aa40-4a31-8eb4-40

                                

media%2F34a%2F34a92245-e55d-4a18-850d-99

  

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


package ch08.trees;

import ch05.queues.*;
import ch03.stacks.*;
import support.BSTNode;    

public class BinarySearchTree<T extends Comparable<T>>
             implements BSTInterface<T>
{
protected BSTNode<T> root;      // reference to the root of this BST

boolean found;   // used by remove

// for traversals
protected LinkedUnbndQueue<T> inOrderQueue;    // queue of info
protected LinkedUnbndQueue<T> preOrderQueue;   // queue of info
protected LinkedUnbndQueue<T> postOrderQueue; // queue of info

public BinarySearchTree()
// Creates an empty BST object.
{
    root = null;
}

public boolean isEmpty()
// Returns true if this BST is empty; otherwise, returns false.
{
    return (root == null);
}

private int recSize(BSTNode<T> tree)
// Returns the number of elements in tree.
{
    if (tree == null)  
      return 0;
    else
      return recSize(tree.getLeft()) + recSize(tree.getRight()) + 1;
}

public int size()
// Returns the number of elements in this BST.
{
    return recSize(root);
}

private int leafCount(BSTNode<T> tree){
      if (tree == null) return 0;
      if (tree.getLeft() == null && tree.getRight() == null) return 1;
      return leafCount(tree.getLeft()) + leafCount(tree.getRight());
}

public int leafCount() {
      return leafCount(root);
}

boolean similarTrees(BSTNode<T> tree1, BSTNode<T> tree2) {
      if (tree1 == null && tree2 == null) return true;
      if (tree1 == null && tree2 != null) return false;
      if (tree1 != null && tree2 == null) return false;
    
      boolean leftSimilarOrNot = similarTrees(tree1.getLeft(), tree2.getLeft());
      boolean rightSimilarOrNot = similarTrees(tree1.getRight(), tree2.getRight());
    
      return leftSimilarOrNot && rightSimilarOrNot;
}

public int size2()
// Returns the number of elements in this BST.
{
    int count = 0;
    if (root != null)
    {
      LinkedStack<BSTNode<T>> hold = new LinkedStack<BSTNode<T>>();
      BSTNode<T> currNode;
      hold.push(root);
      while (!hold.isEmpty())
      {
        currNode = hold.top();
        hold.pop();
        count++;
        if (currNode.getLeft() != null)
          hold.push(currNode.getLeft());
        if (currNode.getRight() != null)
          hold.push(currNode.getRight());
      }
    }
    return count;
}

private boolean recContains(T element, BSTNode<T> tree)
// Returns true if tree contains an element e such that
// e.compareTo(element) == 0; otherwise, returns false.
{
    if (tree == null)
      return false;       // element is not found
    else if (element.compareTo(tree.getInfo()) < 0)
      return recContains(element, tree.getLeft());   // Search left subtree
    else if (element.compareTo(tree.getInfo()) > 0)
      return recContains(element, tree.getRight()); // Search right subtree
    else
      return true;        // element is found
}

public boolean contains (T element)
// Returns true if this BST contains an element e such that
// e.compareTo(element) == 0; otherwise, returns false.
{
    return recContains(element, root);
}

private T recGet(T element, BSTNode<T> tree)
// Returns an element e from tree such that e.compareTo(element) == 0;
// if no such element exists, returns null.
{
    if (tree == null)
      return null;             // element is not found
    else if (element.compareTo(tree.getInfo()) < 0)
      return recGet(element, tree.getLeft());          // get from left subtree
    else
    if (element.compareTo(tree.getInfo()) > 0)
      return recGet(element, tree.getRight());         // get from right subtree
    else
      return tree.getInfo(); // element is found
}

public T get(T element)
// Returns an element e from this BST such that e.compareTo(element) == 0;
// if no such element exists, returns null.
{
    return recGet(element, root);
}

private BSTNode<T> recAdd(T element, BSTNode<T> tree)
// Adds element to tree; tree retains its BST property.
{
    if (tree == null)
      // Addition place found
      tree = new BSTNode<T>(element);
    else if (element.compareTo(tree.getInfo()) <= 0)
      tree.setLeft(recAdd(element, tree.getLeft()));    // Add in left subtree
    else
      tree.setRight(recAdd(element, tree.getRight()));   // Add in right subtree
    return tree;
}

public void add (T element)
// Adds element to this BST. The tree retains its BST property.
{
    root = recAdd(element, root);
}

private T getPredecessor(BSTNode<T> tree)
// Returns the information held in the rightmost node in tree
{
    while (tree.getRight() != null)
      tree = tree.getRight();
    return tree.getInfo();
}

private BSTNode<T> removeNode(BSTNode<T> tree)
// Removes the information at the node referenced by tree.
// The user's data in the node referenced by tree is no
// longer in the tree. If tree is a leaf node or has only
// a non-null child pointer, the node pointed to by tree is
// removed; otherwise, the user's data is replaced by its
// logical predecessor and the predecessor's node is removed.
{
    T data;

    if (tree.getLeft() == null)
      return tree.getRight();
    else if (tree.getRight() == null)
      return tree.getLeft();
    else
    {
      data = getPredecessor(tree.getLeft());
      tree.setInfo(data);
      tree.setLeft(recRemove(data, tree.getLeft()));
      return tree;
    }
}

private BSTNode<T> recRemove(T element, BSTNode<T> tree)
// Removes an element e from tree such that e.compareTo(element) == 0
// and returns true; if no such element exists, returns false.
{
    if (tree == null)
      found = false;
    else if (element.compareTo(tree.getInfo()) < 0)
      tree.setLeft(recRemove(element, tree.getLeft()));
    else if (element.compareTo(tree.getInfo()) > 0)
      tree.setRight(recRemove(element, tree.getRight()));
    else
    {
      tree = removeNode(tree);
      found = true;
   }
    return tree;
}

public boolean remove (T element)
// Removes an element e from this BST such that e.compareTo(element) == 0
// and returns true; if no such element exists, returns false.
{
    root = recRemove(element, root);
    return found;
}

private void inOrder(BSTNode<T> tree)
// Initializes inOrderQueue with tree elements in inOrder order.
{
    if (tree != null)
    {
      inOrder(tree.getLeft());
      inOrderQueue.enqueue(tree.getInfo());
      inOrder(tree.getRight());
    }
}

private void preOrder(BSTNode<T> tree)
// Initializes preOrderQueue with tree elements in preOrder order.
{
    if (tree != null)
    {
      preOrderQueue.enqueue(tree.getInfo());
      preOrder(tree.getLeft());
      preOrder(tree.getRight());
    }
}

private void postOrder(BSTNode<T> tree)
// Initializes postOrderQueue with tree elements in postOrder order.
{
    if (tree != null)
    {
      postOrder(tree.getLeft());
      postOrder(tree.getRight());
      postOrderQueue.enqueue(tree.getInfo());
    }
}

public int reset(int orderType)
// Initializes current position for an iteration through this BST
// in orderType order. Returns current number of nodes in the BST.
{
    int numNodes = size();

    if (orderType == INORDER)
    {
      inOrderQueue = new LinkedUnbndQueue<T>();
      inOrder(root);
    }
    else
    if (orderType == PREORDER)
    {
      preOrderQueue = new LinkedUnbndQueue<T>();
      preOrder(root);
    }
    if (orderType == POSTORDER)
    {
      postOrderQueue = new LinkedUnbndQueue<T>();
      postOrder(root);
    }
    return numNodes;
}

public T getNext (int orderType)
// Preconditions: The BST is not empty
//                The BST has been reset for orderType
//                The BST has not been modified since the most recent reset
//                The end of orderType iteration has not been reached
//
// Returns the element at the current position on this BST for orderType
// and advances the value of the current position based on the orderType.
{
    if (orderType == INORDER)
      return inOrderQueue.dequeue();
    else
    if (orderType == PREORDER)
      return preOrderQueue.dequeue();
    else
    if (orderType == POSTORDER)
      return postOrderQueue.dequeue();
    else return null;
}
}

BSTInterface.java

package ch08.trees;

public interface BSTInterface<T extends Comparable<T>>
{
// used to specify traversal order
static final int INORDER = 1;
static final int PREORDER = 2;
static final int POSTORDER = 3;

boolean isEmpty();
// Returns true if this BST is empty; otherwise, returns false.

int size();
// Returns the number of elements in this BST.

boolean contains (T element);
// Returns true if this BST contains an element e such that
// e.compareTo(element) == 0; otherwise, returns false.
  
boolean remove (T element);
// Removes an element e from this BST such that e.compareTo(element) == 0
// and returns true; if no such element exists, returns false.

T get(T element);
// Returns an element e from this BST such that e.compareTo(element) == 0;
// if no such element exists, returns null.

void add (T element);
// Adds element to this BST. The tree retains its BST property.

int reset(int orderType);
// Initializes current position for an iteration through this BST
// in orderType order. Returns current number of nodes in the BST.

T getNext (int orderType);
// Preconditions: The BST is not empty
//                The BST has been reset for orderType
//                The BST has not been modified since the most recent reset
//                The end of orderType iteration has not been reached
//
// Returns the element at the current position on this BST for orderType
// and advances the value of the current position based on the orderType.
}

Add a comment
Know the answer?
Add Answer to:
1) Extend the Binary Search Tree ADT to include a public method leafCount that returns 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
  • 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...

  • Write a client method that returns a count of the number of nodes in a binary...

    Write a client method that returns a count of the number of nodes in a binary search tree that contain scores less than or equal to a passed-in argument (parameter) value. The method header is: int countLowerScores (BinarySearchTree tree, int maxValue) The BinarySearchTree contains these methods in the picture. public class BinarySearchTreecT> implements BSTInterfacecT> //reference to the root of this BST public BSTNode<T> root; public Comparator<T> comp: IIused for all comparisons public boolean found: / used by remove public BinarYSearchTree()...

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

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

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

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

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

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

  • Add printRang method to BST.java that, given a low key value, and high key value, print...

    Add printRang method to BST.java that, given a low key value, and high key value, print all records in a sorted order whose values fall between the two given keys. (Both low key and high key do not have to be a key on the list). BST.java import java.lang.Comparable; /** Binary Search Tree implementation for Dictionary ADT */ class BST<Key extends Comparable<? super Key>, E> implements Dictionary<Key, E> { private BSTNode<Key,E> root; // Root of the BST int nodecount; //...

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