SlideShare una empresa de Scribd logo
1 de 6
Descargar para leer sin conexión
Add a method levelorderElements() to the BST.java binary search tree
dictionary implementation on Vocareum. In level order the root comes
first, then all nodes of level 1, then all nodes of level 2, and so on. Within
a level, the order is left to right; i.e., in ascending order. Model your
method on inorderElements(). Test your method by changing the calls to
inorderElements() in values() to levelorderElements(). This way, values()
will return the values in the dictionary in level order. Test your class using
the program PrintLevels.java.
Hint: Preorder traversals make use of a stack through recursive calls.
Consider making use of another data structure to help implement the lev-
elorder traversal.
BST class:
import java.util.ArrayList;
/** BST implementation for Dictionary ADT */
class BST<K extends Comparable<K>, E> implements Dictionary<K, E> {
private BSTNode<K, E> root; // Root of BST
private int nodecount; // Size of BST
/** Constructor */
BST() {
root = null;
nodecount = 0;
}
/** Reinitialize tree */
public void clear() {
root = null;
nodecount = 0;
}
/**
* Insert a record into the tree.
*
* @param k
* Key value of the record.
* @param e
* The record to insert.
*/
public void insert(K k, E e) {
root = inserthelp(root, k, e);
nodecount++;
}
/**
* Remove a record from the tree.
*
* @param k
* Key value of record to remove.
* @return Record removed, or null if there is none.
*/
public E remove(K k) {
E temp = findhelp(root, k); // find it
if (temp != null) {
root = removehelp(root, k); // remove it
// System.out.println("called removehelp");
nodecount--;
}
return temp;
}
/**
* Remove/return root node from dictionary.
*
* @return The record removed, null if empty.
*/
public E removeAny() {
if (root == null)
return null;
E temp = root.element();
root = removehelp(root, root.key());
--nodecount;
return temp;
}
/**
* @return Record with key k, null if none.
* @param k
* The key value to find.
*/
public E find(K k) {
return findhelp(root, k);
}
/** @return Number of records in dictionary. */
public int size() {
return nodecount;
}
private E findhelp(BSTNode<K, E> rt, K k) {
if (rt == null)
return null;
if (rt.key().compareTo(k) > 0)
return findhelp(rt.left(), k);
else if (rt.key().compareTo(k) == 0)
return rt.element();
else
return findhelp(rt.right(), k);
}
private BSTNode<K, E> inserthelp(BSTNode<K, E> rt, K k, E e) {
if (rt == null)
return new BSTNode<K, E>(k, e);
if (rt.key().compareTo(k) > 0)
rt.setLeft(inserthelp(rt.left(), k, e));
else
rt.setRight(inserthelp(rt.right(), k, e));
return rt;
}
private BSTNode<K, E> getmin(BSTNode<K, E> rt) {
if (rt.left() == null)
return rt;
else
return getmin(rt.left());
}
private BSTNode<K, E> deletemin(BSTNode<K, E> rt) {
if (rt.left() == null)
return rt.right();
else {
rt.setLeft(deletemin(rt.left()));
return rt;
}
}
/**
* Remove a node with key value k
*
* @return The tree with the node removed
*/
private BSTNode<K, E> removehelp(BSTNode<K, E> rt, K k) {
if (rt == null)
return null;
if (rt.key().compareTo(k) > 0)
rt.setLeft(removehelp(rt.left(), k));
else if (rt.key().compareTo(k) < 0)
rt.setRight(removehelp(rt.right(), k));
else { // Found it, remove it
if (rt.left() == null)
return rt.right();
else if (rt.right() == null)
return rt.left();
else { // Two children
BSTNode<K, E> temp = getmin(rt.right());
rt.setElement(temp.element());
rt.setKey(temp.key());
rt.setRight(deletemin(rt.right()));
}
}
return rt;
}
/**
* Creates a list storing the the nodes in the subtree of a node, ordered
* according to the inorder traversal of the subtree.
*/
protected void inorderElements(BSTNode<K, E> v, ArrayList<E> elts) {
// elts.add(v.element());
if (v.left() != null)
inorderElements(v.left(), elts); // recurse on left child
elts.add(v.element());
if (v.right() != null)
inorderElements(v.right(), elts); // recurse on right child
}
/** Returns an iterable collection of the tree nodes. */
public Iterable<E> values() {
ArrayList<E> elements = new ArrayList<E>();
if (size() != 0)
inorderElements(root, elements); // assign positions in order
return elements;
}
public Iterable<E> findAll(K k) {
ArrayList<E> al = new ArrayList<E>();
findAllhelp(root, k, al);
return al;
}
protected void findAllhelp(BSTNode<K, E> rt, K k, ArrayList<E> a) {
if (rt == null)
return;
if (rt.key().compareTo(k) > 0)
findAllhelp(rt.left(), k, a);
else if (rt.key().compareTo(k) == 0) {
a.add(rt.element());
findAllhelp(rt.right(), k, a);
} else
findAllhelp(rt.right(), k, a);
}
/* the following are for solving the exercises in Shaffer, ch. 5 */
public Iterable<E> range(K a, K b) {
ArrayList<E> elements = new ArrayList<E>();
rangehelp(root, elements, a, b);
return elements;
}
protected void rangehelp(BSTNode<K, E> v, ArrayList<E> elts, K a, K b) {
if (v == null) {
return;
}
if (v.key().compareTo(a) > 0) {
rangehelp(v.left(), elts, a, b);
}
if (v.key().compareTo(a) >= 0 && v.key().compareTo(b) <= 0) {
elts.add(v.element());
}
if (v.key().compareTo(b) < 0) {
rangehelp(v.right(), elts, a, b);
}
}
}
PrintRange class:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.ArrayList;
/*
* Print out all dictionary records in a given range of keys.
*/
public class PrintRange {
public static void main(String[] args) {
BST<String, Pronunciation> PDict = new BST<String, Pronunciation>();
File file = new File("shuffledDictionary.txt");
// Read in the (shuffled) cmu pronunciation dictionary.
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (line.substring(0, 3).equals(";;;"))
continue; // skip comment lines
Pronunciation p = new Pronunciation(line);
PDict.insert(p.getWord(), p); // key dictionary on word
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Scanner input = new Scanner(System.in);
String a = input.next(); // first word in range
String b = input.next(); // last word in range
for(Pronunciation p : PDict.range(a,b))
System.out.println(p.getWord()+" "+p.getPhonemes());
}
}

Más contenido relacionado

Similar a Add a method levelorderElements() to the BST-java binary search tree d.pdf

A perfect left-sided binary tree is a binary tree where every intern.pdf
A perfect left-sided binary tree is a binary tree where every intern.pdfA perfect left-sided binary tree is a binary tree where every intern.pdf
A perfect left-sided binary tree is a binary tree where every intern.pdfmichardsonkhaicarr37
 
Complete code in Java The hashtable you'll be making will use String.pdf
Complete code in Java   The hashtable you'll be making will use String.pdfComplete code in Java   The hashtable you'll be making will use String.pdf
Complete code in Java The hashtable you'll be making will use String.pdfaarifi9988
 
The hashtable youll be making will use Strings as the keys and Obje.pdf
The hashtable youll be making will use Strings as the keys and Obje.pdfThe hashtable youll be making will use Strings as the keys and Obje.pdf
The hashtable youll be making will use Strings as the keys and Obje.pdfvicky309441
 
Write a program that displays an AVL tree along with its balance fac.docx
 Write a program that displays an AVL tree  along with its balance fac.docx Write a program that displays an AVL tree  along with its balance fac.docx
Write a program that displays an AVL tree along with its balance fac.docxajoy21
 
ReversePoem.java ---------------------------------- public cl.pdf
ReversePoem.java ---------------------------------- public cl.pdfReversePoem.java ---------------------------------- public cl.pdf
ReversePoem.java ---------------------------------- public cl.pdfravikapoorindia
 
Given below is the completed implementation of MyLinkedList class. O.pdf
Given below is the completed implementation of MyLinkedList class. O.pdfGiven below is the completed implementation of MyLinkedList class. O.pdf
Given below is the completed implementation of MyLinkedList class. O.pdfinfo430661
 
Describe a data structure to represent sets of elements (each element.pdf
Describe a data structure to represent sets of elements (each element.pdfDescribe a data structure to represent sets of elements (each element.pdf
Describe a data structure to represent sets of elements (each element.pdfrajeshjain2109
 
in C++ , Design a linked list class named IntegerList to hold a seri.pdf
in C++ , Design a linked list class named IntegerList to hold a seri.pdfin C++ , Design a linked list class named IntegerList to hold a seri.pdf
in C++ , Design a linked list class named IntegerList to hold a seri.pdfeyewaregallery
 
So I have this code(StackInAllSocks) and I implemented the method but.pdf
So I have this code(StackInAllSocks) and I implemented the method but.pdfSo I have this code(StackInAllSocks) and I implemented the method but.pdf
So I have this code(StackInAllSocks) and I implemented the method but.pdfaksahnan
 
Underscore.js
Underscore.jsUnderscore.js
Underscore.jstimourian
 
Data Types and Processing in ES6
Data Types and Processing in ES6Data Types and Processing in ES6
Data Types and Processing in ES6m0bz
 
Implement the additional 5 methods as indicated in the LinkedList fi.pdf
Implement the additional 5 methods as indicated in the LinkedList fi.pdfImplement the additional 5 methods as indicated in the LinkedList fi.pdf
Implement the additional 5 methods as indicated in the LinkedList fi.pdffootstatus
 
I need help writing test Codepackage org.example;import j.pdf
I need help writing test Codepackage org.example;import j.pdfI need help writing test Codepackage org.example;import j.pdf
I need help writing test Codepackage org.example;import j.pdfmail931892
 
import java.util.Scanner;class BinaryNode{     BinaryNode left.pdf
import java.util.Scanner;class BinaryNode{     BinaryNode left.pdfimport java.util.Scanner;class BinaryNode{     BinaryNode left.pdf
import java.util.Scanner;class BinaryNode{     BinaryNode left.pdfshaktisinhgandhinaga
 
In this lab, you will be given a simple code for a min Heap, and you.pdf
In this lab, you will be given a simple code for a min Heap, and you.pdfIn this lab, you will be given a simple code for a min Heap, and you.pdf
In this lab, you will be given a simple code for a min Heap, and you.pdfcharanjit1717
 

Similar a Add a method levelorderElements() to the BST-java binary search tree d.pdf (20)

A perfect left-sided binary tree is a binary tree where every intern.pdf
A perfect left-sided binary tree is a binary tree where every intern.pdfA perfect left-sided binary tree is a binary tree where every intern.pdf
A perfect left-sided binary tree is a binary tree where every intern.pdf
 
Complete code in Java The hashtable you'll be making will use String.pdf
Complete code in Java   The hashtable you'll be making will use String.pdfComplete code in Java   The hashtable you'll be making will use String.pdf
Complete code in Java The hashtable you'll be making will use String.pdf
 
Spark_Documentation_Template1
Spark_Documentation_Template1Spark_Documentation_Template1
Spark_Documentation_Template1
 
The hashtable youll be making will use Strings as the keys and Obje.pdf
The hashtable youll be making will use Strings as the keys and Obje.pdfThe hashtable youll be making will use Strings as the keys and Obje.pdf
The hashtable youll be making will use Strings as the keys and Obje.pdf
 
2014-11-01 01 Денис Нелюбин. О сортах кофе
2014-11-01 01 Денис Нелюбин. О сортах кофе2014-11-01 01 Денис Нелюбин. О сортах кофе
2014-11-01 01 Денис Нелюбин. О сортах кофе
 
Write a program that displays an AVL tree along with its balance fac.docx
 Write a program that displays an AVL tree  along with its balance fac.docx Write a program that displays an AVL tree  along with its balance fac.docx
Write a program that displays an AVL tree along with its balance fac.docx
 
Java Generics
Java GenericsJava Generics
Java Generics
 
ReversePoem.java ---------------------------------- public cl.pdf
ReversePoem.java ---------------------------------- public cl.pdfReversePoem.java ---------------------------------- public cl.pdf
ReversePoem.java ---------------------------------- public cl.pdf
 
collections
collectionscollections
collections
 
Given below is the completed implementation of MyLinkedList class. O.pdf
Given below is the completed implementation of MyLinkedList class. O.pdfGiven below is the completed implementation of MyLinkedList class. O.pdf
Given below is the completed implementation of MyLinkedList class. O.pdf
 
Describe a data structure to represent sets of elements (each element.pdf
Describe a data structure to represent sets of elements (each element.pdfDescribe a data structure to represent sets of elements (each element.pdf
Describe a data structure to represent sets of elements (each element.pdf
 
in C++ , Design a linked list class named IntegerList to hold a seri.pdf
in C++ , Design a linked list class named IntegerList to hold a seri.pdfin C++ , Design a linked list class named IntegerList to hold a seri.pdf
in C++ , Design a linked list class named IntegerList to hold a seri.pdf
 
So I have this code(StackInAllSocks) and I implemented the method but.pdf
So I have this code(StackInAllSocks) and I implemented the method but.pdfSo I have this code(StackInAllSocks) and I implemented the method but.pdf
So I have this code(StackInAllSocks) and I implemented the method but.pdf
 
Underscore.js
Underscore.jsUnderscore.js
Underscore.js
 
Interpreter Case Study - Design Patterns
Interpreter Case Study - Design PatternsInterpreter Case Study - Design Patterns
Interpreter Case Study - Design Patterns
 
Data Types and Processing in ES6
Data Types and Processing in ES6Data Types and Processing in ES6
Data Types and Processing in ES6
 
Implement the additional 5 methods as indicated in the LinkedList fi.pdf
Implement the additional 5 methods as indicated in the LinkedList fi.pdfImplement the additional 5 methods as indicated in the LinkedList fi.pdf
Implement the additional 5 methods as indicated in the LinkedList fi.pdf
 
I need help writing test Codepackage org.example;import j.pdf
I need help writing test Codepackage org.example;import j.pdfI need help writing test Codepackage org.example;import j.pdf
I need help writing test Codepackage org.example;import j.pdf
 
import java.util.Scanner;class BinaryNode{     BinaryNode left.pdf
import java.util.Scanner;class BinaryNode{     BinaryNode left.pdfimport java.util.Scanner;class BinaryNode{     BinaryNode left.pdf
import java.util.Scanner;class BinaryNode{     BinaryNode left.pdf
 
In this lab, you will be given a simple code for a min Heap, and you.pdf
In this lab, you will be given a simple code for a min Heap, and you.pdfIn this lab, you will be given a simple code for a min Heap, and you.pdf
In this lab, you will be given a simple code for a min Heap, and you.pdf
 

Más de amolawachat

An aircraft leaves a city at latitude 1 and longitude 1 and flies to a.pdf
An aircraft leaves a city at latitude 1 and longitude 1 and flies to a.pdfAn aircraft leaves a city at latitude 1 and longitude 1 and flies to a.pdf
An aircraft leaves a city at latitude 1 and longitude 1 and flies to a.pdfamolawachat
 
Among these statements- which is the only one part of the GDP- A- Pedr.pdf
Among these statements- which is the only one part of the GDP- A- Pedr.pdfAmong these statements- which is the only one part of the GDP- A- Pedr.pdf
Among these statements- which is the only one part of the GDP- A- Pedr.pdfamolawachat
 
Among the guiding principles of six sigma are (I) Reduction of variati.pdf
Among the guiding principles of six sigma are (I) Reduction of variati.pdfAmong the guiding principles of six sigma are (I) Reduction of variati.pdf
Among the guiding principles of six sigma are (I) Reduction of variati.pdfamolawachat
 
Amoeba are motile unicellular eukaryotes that obtain energy and nutrie.pdf
Amoeba are motile unicellular eukaryotes that obtain energy and nutrie.pdfAmoeba are motile unicellular eukaryotes that obtain energy and nutrie.pdf
Amoeba are motile unicellular eukaryotes that obtain energy and nutrie.pdfamolawachat
 
Aloha Education Center is providing it education service in a number o.pdf
Aloha Education Center is providing it education service in a number o.pdfAloha Education Center is providing it education service in a number o.pdf
Aloha Education Center is providing it education service in a number o.pdfamolawachat
 
Allele H- for the ability to tolerate Newcastle infection is dominant.pdf
Allele H- for the ability to tolerate Newcastle infection is dominant.pdfAllele H- for the ability to tolerate Newcastle infection is dominant.pdf
Allele H- for the ability to tolerate Newcastle infection is dominant.pdfamolawachat
 
All parts of the Earth do not receive the same amount of radiation- Th.pdf
All parts of the Earth do not receive the same amount of radiation- Th.pdfAll parts of the Earth do not receive the same amount of radiation- Th.pdf
All parts of the Earth do not receive the same amount of radiation- Th.pdfamolawachat
 
All of the muscles listed below originate on the medial epicondyle of.pdf
All of the muscles listed below originate on the medial epicondyle of.pdfAll of the muscles listed below originate on the medial epicondyle of.pdf
All of the muscles listed below originate on the medial epicondyle of.pdfamolawachat
 
All of these are common products of subduction zone volcanoes except-.pdf
All of these are common products of subduction zone volcanoes except-.pdfAll of these are common products of subduction zone volcanoes except-.pdf
All of these are common products of subduction zone volcanoes except-.pdfamolawachat
 
All of the following apply to Quorum sensing EXCEPT (choose the false.pdf
All of the following apply to Quorum sensing EXCEPT (choose the false.pdfAll of the following apply to Quorum sensing EXCEPT (choose the false.pdf
All of the following apply to Quorum sensing EXCEPT (choose the false.pdfamolawachat
 
All of the following are true regarding exotic streams EXCEPT- They ha.pdf
All of the following are true regarding exotic streams EXCEPT- They ha.pdfAll of the following are true regarding exotic streams EXCEPT- They ha.pdf
All of the following are true regarding exotic streams EXCEPT- They ha.pdfamolawachat
 
All of the following apply to DNA binding proteins EXCEPT (Choose the.pdf
All of the following apply to DNA binding proteins EXCEPT (Choose the.pdfAll of the following apply to DNA binding proteins EXCEPT (Choose the.pdf
All of the following apply to DNA binding proteins EXCEPT (Choose the.pdfamolawachat
 
All are ways firms can accelerate in innovation except- Question 8 opt.pdf
All are ways firms can accelerate in innovation except- Question 8 opt.pdfAll are ways firms can accelerate in innovation except- Question 8 opt.pdf
All are ways firms can accelerate in innovation except- Question 8 opt.pdfamolawachat
 
All are reasons for sampling except A- The sample can save money- B- T.pdf
All are reasons for sampling except A- The sample can save money- B- T.pdfAll are reasons for sampling except A- The sample can save money- B- T.pdf
All are reasons for sampling except A- The sample can save money- B- T.pdfamolawachat
 
Algorithms problem Given a class called Book which has four private me.pdf
Algorithms problem Given a class called Book which has four private me.pdfAlgorithms problem Given a class called Book which has four private me.pdf
Algorithms problem Given a class called Book which has four private me.pdfamolawachat
 
Albinism is a recessive trait- A man and woman both show normal pigmen.pdf
Albinism is a recessive trait- A man and woman both show normal pigmen.pdfAlbinism is a recessive trait- A man and woman both show normal pigmen.pdf
Albinism is a recessive trait- A man and woman both show normal pigmen.pdfamolawachat
 
Albedo- or reflectivity- is expressed as a percentage- Materials like.pdf
Albedo- or reflectivity- is expressed as a percentage- Materials like.pdfAlbedo- or reflectivity- is expressed as a percentage- Materials like.pdf
Albedo- or reflectivity- is expressed as a percentage- Materials like.pdfamolawachat
 
After reading all Lesson 8 materials- research an international news s.pdf
After reading all Lesson 8 materials- research an international news s.pdfAfter reading all Lesson 8 materials- research an international news s.pdf
After reading all Lesson 8 materials- research an international news s.pdfamolawachat
 
After reading Talent- Transformation- and the Triple Bottom Line by A-.pdf
After reading Talent- Transformation- and the Triple Bottom Line by A-.pdfAfter reading Talent- Transformation- and the Triple Bottom Line by A-.pdf
After reading Talent- Transformation- and the Triple Bottom Line by A-.pdfamolawachat
 
Adjust the following to prepare the statement of cash flows using the.pdf
Adjust the following to prepare the statement of cash flows using the.pdfAdjust the following to prepare the statement of cash flows using the.pdf
Adjust the following to prepare the statement of cash flows using the.pdfamolawachat
 

Más de amolawachat (20)

An aircraft leaves a city at latitude 1 and longitude 1 and flies to a.pdf
An aircraft leaves a city at latitude 1 and longitude 1 and flies to a.pdfAn aircraft leaves a city at latitude 1 and longitude 1 and flies to a.pdf
An aircraft leaves a city at latitude 1 and longitude 1 and flies to a.pdf
 
Among these statements- which is the only one part of the GDP- A- Pedr.pdf
Among these statements- which is the only one part of the GDP- A- Pedr.pdfAmong these statements- which is the only one part of the GDP- A- Pedr.pdf
Among these statements- which is the only one part of the GDP- A- Pedr.pdf
 
Among the guiding principles of six sigma are (I) Reduction of variati.pdf
Among the guiding principles of six sigma are (I) Reduction of variati.pdfAmong the guiding principles of six sigma are (I) Reduction of variati.pdf
Among the guiding principles of six sigma are (I) Reduction of variati.pdf
 
Amoeba are motile unicellular eukaryotes that obtain energy and nutrie.pdf
Amoeba are motile unicellular eukaryotes that obtain energy and nutrie.pdfAmoeba are motile unicellular eukaryotes that obtain energy and nutrie.pdf
Amoeba are motile unicellular eukaryotes that obtain energy and nutrie.pdf
 
Aloha Education Center is providing it education service in a number o.pdf
Aloha Education Center is providing it education service in a number o.pdfAloha Education Center is providing it education service in a number o.pdf
Aloha Education Center is providing it education service in a number o.pdf
 
Allele H- for the ability to tolerate Newcastle infection is dominant.pdf
Allele H- for the ability to tolerate Newcastle infection is dominant.pdfAllele H- for the ability to tolerate Newcastle infection is dominant.pdf
Allele H- for the ability to tolerate Newcastle infection is dominant.pdf
 
All parts of the Earth do not receive the same amount of radiation- Th.pdf
All parts of the Earth do not receive the same amount of radiation- Th.pdfAll parts of the Earth do not receive the same amount of radiation- Th.pdf
All parts of the Earth do not receive the same amount of radiation- Th.pdf
 
All of the muscles listed below originate on the medial epicondyle of.pdf
All of the muscles listed below originate on the medial epicondyle of.pdfAll of the muscles listed below originate on the medial epicondyle of.pdf
All of the muscles listed below originate on the medial epicondyle of.pdf
 
All of these are common products of subduction zone volcanoes except-.pdf
All of these are common products of subduction zone volcanoes except-.pdfAll of these are common products of subduction zone volcanoes except-.pdf
All of these are common products of subduction zone volcanoes except-.pdf
 
All of the following apply to Quorum sensing EXCEPT (choose the false.pdf
All of the following apply to Quorum sensing EXCEPT (choose the false.pdfAll of the following apply to Quorum sensing EXCEPT (choose the false.pdf
All of the following apply to Quorum sensing EXCEPT (choose the false.pdf
 
All of the following are true regarding exotic streams EXCEPT- They ha.pdf
All of the following are true regarding exotic streams EXCEPT- They ha.pdfAll of the following are true regarding exotic streams EXCEPT- They ha.pdf
All of the following are true regarding exotic streams EXCEPT- They ha.pdf
 
All of the following apply to DNA binding proteins EXCEPT (Choose the.pdf
All of the following apply to DNA binding proteins EXCEPT (Choose the.pdfAll of the following apply to DNA binding proteins EXCEPT (Choose the.pdf
All of the following apply to DNA binding proteins EXCEPT (Choose the.pdf
 
All are ways firms can accelerate in innovation except- Question 8 opt.pdf
All are ways firms can accelerate in innovation except- Question 8 opt.pdfAll are ways firms can accelerate in innovation except- Question 8 opt.pdf
All are ways firms can accelerate in innovation except- Question 8 opt.pdf
 
All are reasons for sampling except A- The sample can save money- B- T.pdf
All are reasons for sampling except A- The sample can save money- B- T.pdfAll are reasons for sampling except A- The sample can save money- B- T.pdf
All are reasons for sampling except A- The sample can save money- B- T.pdf
 
Algorithms problem Given a class called Book which has four private me.pdf
Algorithms problem Given a class called Book which has four private me.pdfAlgorithms problem Given a class called Book which has four private me.pdf
Algorithms problem Given a class called Book which has four private me.pdf
 
Albinism is a recessive trait- A man and woman both show normal pigmen.pdf
Albinism is a recessive trait- A man and woman both show normal pigmen.pdfAlbinism is a recessive trait- A man and woman both show normal pigmen.pdf
Albinism is a recessive trait- A man and woman both show normal pigmen.pdf
 
Albedo- or reflectivity- is expressed as a percentage- Materials like.pdf
Albedo- or reflectivity- is expressed as a percentage- Materials like.pdfAlbedo- or reflectivity- is expressed as a percentage- Materials like.pdf
Albedo- or reflectivity- is expressed as a percentage- Materials like.pdf
 
After reading all Lesson 8 materials- research an international news s.pdf
After reading all Lesson 8 materials- research an international news s.pdfAfter reading all Lesson 8 materials- research an international news s.pdf
After reading all Lesson 8 materials- research an international news s.pdf
 
After reading Talent- Transformation- and the Triple Bottom Line by A-.pdf
After reading Talent- Transformation- and the Triple Bottom Line by A-.pdfAfter reading Talent- Transformation- and the Triple Bottom Line by A-.pdf
After reading Talent- Transformation- and the Triple Bottom Line by A-.pdf
 
Adjust the following to prepare the statement of cash flows using the.pdf
Adjust the following to prepare the statement of cash flows using the.pdfAdjust the following to prepare the statement of cash flows using the.pdf
Adjust the following to prepare the statement of cash flows using the.pdf
 

Último

Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingTeacherCyreneCayanan
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024Janet Corral
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 

Último (20)

Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 

Add a method levelorderElements() to the BST-java binary search tree d.pdf

  • 1. Add a method levelorderElements() to the BST.java binary search tree dictionary implementation on Vocareum. In level order the root comes first, then all nodes of level 1, then all nodes of level 2, and so on. Within a level, the order is left to right; i.e., in ascending order. Model your method on inorderElements(). Test your method by changing the calls to inorderElements() in values() to levelorderElements(). This way, values() will return the values in the dictionary in level order. Test your class using the program PrintLevels.java. Hint: Preorder traversals make use of a stack through recursive calls. Consider making use of another data structure to help implement the lev- elorder traversal. BST class: import java.util.ArrayList; /** BST implementation for Dictionary ADT */ class BST<K extends Comparable<K>, E> implements Dictionary<K, E> { private BSTNode<K, E> root; // Root of BST private int nodecount; // Size of BST /** Constructor */ BST() { root = null; nodecount = 0; } /** Reinitialize tree */ public void clear() { root = null; nodecount = 0; } /** * Insert a record into the tree. * * @param k * Key value of the record. * @param e * The record to insert. */ public void insert(K k, E e) { root = inserthelp(root, k, e); nodecount++; }
  • 2. /** * Remove a record from the tree. * * @param k * Key value of record to remove. * @return Record removed, or null if there is none. */ public E remove(K k) { E temp = findhelp(root, k); // find it if (temp != null) { root = removehelp(root, k); // remove it // System.out.println("called removehelp"); nodecount--; } return temp; } /** * Remove/return root node from dictionary. * * @return The record removed, null if empty. */ public E removeAny() { if (root == null) return null; E temp = root.element(); root = removehelp(root, root.key()); --nodecount; return temp; } /** * @return Record with key k, null if none. * @param k * The key value to find. */ public E find(K k) { return findhelp(root, k); } /** @return Number of records in dictionary. */ public int size() { return nodecount; }
  • 3. private E findhelp(BSTNode<K, E> rt, K k) { if (rt == null) return null; if (rt.key().compareTo(k) > 0) return findhelp(rt.left(), k); else if (rt.key().compareTo(k) == 0) return rt.element(); else return findhelp(rt.right(), k); } private BSTNode<K, E> inserthelp(BSTNode<K, E> rt, K k, E e) { if (rt == null) return new BSTNode<K, E>(k, e); if (rt.key().compareTo(k) > 0) rt.setLeft(inserthelp(rt.left(), k, e)); else rt.setRight(inserthelp(rt.right(), k, e)); return rt; } private BSTNode<K, E> getmin(BSTNode<K, E> rt) { if (rt.left() == null) return rt; else return getmin(rt.left()); } private BSTNode<K, E> deletemin(BSTNode<K, E> rt) { if (rt.left() == null) return rt.right(); else { rt.setLeft(deletemin(rt.left())); return rt; } } /** * Remove a node with key value k * * @return The tree with the node removed */ private BSTNode<K, E> removehelp(BSTNode<K, E> rt, K k) { if (rt == null) return null;
  • 4. if (rt.key().compareTo(k) > 0) rt.setLeft(removehelp(rt.left(), k)); else if (rt.key().compareTo(k) < 0) rt.setRight(removehelp(rt.right(), k)); else { // Found it, remove it if (rt.left() == null) return rt.right(); else if (rt.right() == null) return rt.left(); else { // Two children BSTNode<K, E> temp = getmin(rt.right()); rt.setElement(temp.element()); rt.setKey(temp.key()); rt.setRight(deletemin(rt.right())); } } return rt; } /** * Creates a list storing the the nodes in the subtree of a node, ordered * according to the inorder traversal of the subtree. */ protected void inorderElements(BSTNode<K, E> v, ArrayList<E> elts) { // elts.add(v.element()); if (v.left() != null) inorderElements(v.left(), elts); // recurse on left child elts.add(v.element()); if (v.right() != null) inorderElements(v.right(), elts); // recurse on right child } /** Returns an iterable collection of the tree nodes. */ public Iterable<E> values() { ArrayList<E> elements = new ArrayList<E>(); if (size() != 0) inorderElements(root, elements); // assign positions in order return elements; } public Iterable<E> findAll(K k) { ArrayList<E> al = new ArrayList<E>(); findAllhelp(root, k, al); return al; }
  • 5. protected void findAllhelp(BSTNode<K, E> rt, K k, ArrayList<E> a) { if (rt == null) return; if (rt.key().compareTo(k) > 0) findAllhelp(rt.left(), k, a); else if (rt.key().compareTo(k) == 0) { a.add(rt.element()); findAllhelp(rt.right(), k, a); } else findAllhelp(rt.right(), k, a); } /* the following are for solving the exercises in Shaffer, ch. 5 */ public Iterable<E> range(K a, K b) { ArrayList<E> elements = new ArrayList<E>(); rangehelp(root, elements, a, b); return elements; } protected void rangehelp(BSTNode<K, E> v, ArrayList<E> elts, K a, K b) { if (v == null) { return; } if (v.key().compareTo(a) > 0) { rangehelp(v.left(), elts, a, b); } if (v.key().compareTo(a) >= 0 && v.key().compareTo(b) <= 0) { elts.add(v.element()); } if (v.key().compareTo(b) < 0) { rangehelp(v.right(), elts, a, b); } } } PrintRange class: import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; import java.util.ArrayList; /* * Print out all dictionary records in a given range of keys.
  • 6. */ public class PrintRange { public static void main(String[] args) { BST<String, Pronunciation> PDict = new BST<String, Pronunciation>(); File file = new File("shuffledDictionary.txt"); // Read in the (shuffled) cmu pronunciation dictionary. try { Scanner scanner = new Scanner(file); while (scanner.hasNextLine()) { String line = scanner.nextLine(); if (line.substring(0, 3).equals(";;;")) continue; // skip comment lines Pronunciation p = new Pronunciation(line); PDict.insert(p.getWord(), p); // key dictionary on word } scanner.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } Scanner input = new Scanner(System.in); String a = input.next(); // first word in range String b = input.next(); // last word in range for(Pronunciation p : PDict.range(a,b)) System.out.println(p.getWord()+" "+p.getPhonemes()); } }