The document provides instructions for augmenting a Binary Search Tree (BST) class to support new operations like returning the nth element, rank of an element, median element, and determining if the tree is perfect or complete. It explains that these operations could be done with in-order traversal but would be inefficient. Instead, each node should store the size of its subtree to guide searches more efficiently. The BST class code is provided to test the augmented operations on.
Once you have all the structures working as intended- it is time to co.docxfarrahkur54
Once you have all the structures working as intended, it is time to compare the
performances of the 2. Use runBenchmark() to start.
a. First, generate an increasing number (N) of random integers (1000, 5000, 10000,
50000, 75000, 100000, 500000 or as far as your computing power will let you)
i. Time and print how long it takes to insert the random integers into an initially
empty BST. Do not print the tree.
You can get a random list using the java class Random, located in
java.util.Random. To test the speed of the insertion algorithm, you should use
the System.currentTimeMillis() method, which returns a long that contains the
current time (in milliseconds). Call System.currentTimeMillis() before and after
the algorithm runs and subtract the two times. (Instant.now() is an alternative
way of recording the time.)
ii. Time and print how long it takes to insert the same random integers into an
initially empty AVL tree. Do not print the tree.
iii. If T(N) is the time function, how does the growth of TBST(N) compare with the
growth of TAVL(N)?
Plot a simple graph to of time against N for the two types of BSTs to visualize
your results.
b. Second, generate a list of k random integers. k is also some large value.
i. Time how long it takes to search your various N-node BSTs for all k random
integers. It does not matter whether the search succeeds.
ii. Time how long it takes to search your N-node AVL trees for the same k random
integers.
iii. Compare the growth rates of these two search time-functions with a graph the
same way you did in part a.
public class BinarySearchTree<AnyType extends Comparable<? super AnyType>> {
protected BinaryNode<AnyType> root;
public BinarySearchTree() {
root = null;
}
/**
* Insert into the tree; duplicates are ignored.
*
* @param x the item to insert.
* @param root
* @return
*/
protected BinaryNode<AnyType> insert(AnyType x, BinaryNode<AnyType> root) {
// If the root is null, we've reached an empty leaf node, so we create a new node
// with the value x and return it
if (root == null) {
return new BinaryNode<>(x, null, null);
}
// Compare the value of x to the value stored in the root node
int compareResult = x.compareTo(root.element);
// If x is less than the value stored in the root node, we insert it into the left subtree
if (compareResult < 0) {
root.left = insert(x, root.left);
}
// If x is greater than the value stored in the root node, we insert it into the right subtree
else if (compareResult > 0) {
root.right = insert(x, root.right);
}
// If x is equal to the value stored in the root node, we ignore it since the tree does not allow duplicates
return root;
}
/**
* Counts the number of leaf nodes in this tree.
*
* @param t The root of the tree.
* @return
*/
private int countLeafNodes(BinaryNode<AnyType> root) {
// If the root is null, it means the tree is empty, so we return 0
if (root == null) {
return 0;
}
// If the root has no children, it means it is a leaf node, so we return 1
if (root.left == .
Tree Traversals A tree traversal is the process of visiting.pdfajayadinathcomputers
Tree Traversals
A tree traversal is the process of "visiting" each node of a tree in some particular order. For a
binary search tree, we can talk about an inorder traversal and a preorder traversal. For this
assignment you are to implement both of these traversals in the code that was started in class.
File bstree.h contains the BSTree class that was developed during class (with the addition of
comments which were omitted by your instructor due to time constraints). The class contains two
inorder functions, one public and one private, and two preorder functions, also one public and one
private. As was the case with other functions implemented for this class, the public versions of
these functions simply call the private versions passing the root node (pointer) as a parameter.
The private versions carry out their actions on the subtree rooted at the given node.
The code provided in bstree.h is missing the implementations for the private inorder and preorder
functions. The coding part of this assignment is to implement these two functions.
When completed, the test program provided should produce the following output:
Values stored in the tree are:
bird
cat
deer
dog
giraffe
groundhog
horse
snake
turtle
The structure of the tree is as follows:
dog
-bird
--cat
---deer
-turtle
--giraffe
---snake
----groundhog
-----horse
Copied!
Written Part
In addition to the coding noted above, give an analysis of all public member functions of the class,
including all constructors, the destructor, and the overload of the assignment operator. For your
analysis you may assume a well-balanced tree (whereas a lopsided tree might lead to a different
analysis).
bstree.h
#pragma once
// A Binary Search Tree implementation.
template <typename T>
class BSTree {
private:
// A node in the tree. Each node has pointers to its left and right nodes
// as well as its parent. When a node is created, the parent and data item
// must be provided.
class node {
public:
T data;
node* left;
node* right;
node* parent;
node (const T& d, node* p) {
parent = p;
data = d;
left = right = nullptr;
}
};
// Pointer to the root node. Initially this is null for an empty tree.
node* root;
// Copy the subtree of another BSTree object into this object. Used by
// the copy constructor and assignment operator.
void copy (node* p) {
if (p) { // If p points to a node...
insert(p->data); // Insert data item
copy(p->left); // Copy the left subtree
copy(p->right); // Copy the right subtree
}
}
// Destroy a node and all nodes in both subtrees. Called by the
// destructor.
void destroy (node* p) {
if (p) { // If p is not null...
destroy(p->left); // Destroy the left subtree
destroy(p->right); // Destroy the right subtree
delete p; // Destroy the node
}
}
// Helper function to determine if a data value is contained in the tree.
// Takes the data value being searched and a pointer to the node in the
// tree. Returns pointer to node in which data item is found, a null
// pointer otherwise.
node* find (const T& .
4. The size of instructions can be fixed or variable. What are advant.pdfmumnesh
4. The size of instructions can be fixed or variable. What are advantage and disadvantage of
fixed compared to variable? point) eft 2 20 0 C-4131-28 Add suction 131-26 nvaction 125-2 PC
egister daiess mancion 120-16 date 1 regnter 2 nstructien 31-00 eg stcrs Read U ALLu dela tlata
dvts 02 rstend In the above figure (single-cycle implementation), current instruction is SW S1,
4(S2) (SW: Store Word; current addrss for this instruction is 100 in decimal; S1 and $2 are
initially 8). For redundancy, you should write \"X\" instead of 0 or . You should write the reason
for cach question as well. 5. What is the value of RegDst? (1 point) 6. What is the value of
RegWrite? (I point) 7. What is the value after sign-extension? 1 point) 8. What is the value of
MemRead? (1 point) 9. What is the value of MemtoReg? (1 point) In the above figure, current
instruction is ADDI $1. S2, #-1(which is minus l) (ADDI is ADD Immediate; current address for
this instruction s 100 in decimal and S2 are initially1). For redundancy, you should write “X\',
instead of 0 or 1 . You should write the reason for each question as well. 10. What is the value
(immediate value) of instruction [15-0)? Write the value in 6-bit binary (1 point) 11. What is the
value after sign extension? Write the value in 32-bit binary. (I point) 12. What is the value of
Reg Write? (1 point) 13. What is the value of MemtoReg? (1 point) 2/4
Solution
import java.util.AbstractSet; import java.util.Arrays; import java.util.Iterator; import
java.util.NoSuchElementException; /** * Implementation of an abstract set using an array-
based binary tree. This is * used to help teach binary tree\'s and will have more details explained
in * future lectures. * * @author William J. Collins * @author Matthew Hertz * @param
Data type (which must be Comparable) of the elements in this tree. */ public class
ArrayBinaryTree> extends AbstractSet { /** Entry in the data store where the root node can be
found. */ private static final int ROOT = 0; /** Array used to store the nodes which consist of
this binary tree. */ protected Node[] store; /** Number of elements within the tree. */
protected int size; /** * Initializes this ArrayBinaryTree object to be empty. This creates the
array * in which items will be stored. */ @SuppressWarnings(\"unchecked\") public
ArrayBinaryTree() { store = new Node[63]; size = 0; } /** * Initializes this
ArrayBinaryTree object to contain a shallow copy of a * specified ArrayBinaryTree object.
The worstTime(n) is O(n), where n is the * number of elements in the specified
ArrayBinaryTree object. * * @param otherTree The tree which will be copied to create our
new tree, */ @SuppressWarnings(\"unchecked\") public ArrayBinaryTree(ArrayBinaryTree
otherTree) { store = (Node[]) Arrays.copyOf(otherTree.store, otherTree.store.length); size =
otherTree.size; } public int countLeaves() { } /** * Returns the size of this
ArrayBinaryTree object. * * @return the size of this ArrayBinaryTree object. */
@Overrid.
JAVA - Design a data structure IntSet that can hold a set of integers-.docxolsenlinnea427
JAVA - Design a data structure IntSet that can hold a set of integers. Hide the private implementation: a Binary Search Tree of Integer objects. Provide the following public methods only.
• Constructor to make an empty set,
• Constructor to create a set by initializing the root,
• void add(int x) to add x if it is not present,
• void remove(int x) to remove x if it is present,
• void print() to print all the elements currently in the set,
• boolean contains(int x) to test whether x is present,
• IntSet copy() to create a new BTS as a copy of the current one.
Note that the root of the BST is a private data member and there is no need to define getRoot(), and setRoot() functions. All the above functions should be defined public and should call recursive private functions to do the task. e.g.
// remove
private Node recRemove(Node loc, int x) { // To do }
public void remove(int x) { root= recRemove(root, x) ; }
// contains
private boolean recContains(Node loc, int x) { // to do }
public boolean contains(int x) { return recContains(root, x) ; }
Complete the class IntSet by supplying the intersection and union functions. Use the same format as above i.e. each public function calls a private recursive function to do the task:
public IntSet union(IntSet other)
public IntSet intersection(IntSet other)
Solution
import java.util.Scanner; class BinarySearchExample { public static void main(String args[]) { int counter, num, item, array[], first, last, middle; //To capture user input Scanner input = new Scanner(System.in); System.out.println(\"Enter number of elements:\"); num = input.nextInt(); //Creating array to store the all the numbers array = new int[num]; System.out.println(\"Enter \" + num + \" integers\"); //Loop to store each numbers in array for (counter = 0; counter < num; counter++) array[counter] = input.nextInt(); System.out.println(\"Enter the search value:\"); item = input.nextInt(); first = 0; last = num - 1; middle = (first + last)/2; while( first <= last ) { if ( array[middle] < item ) first = middle + 1; else if ( array[middle] == item ) { System.out.println(item + \" found at location \" + (middle + 1) + \".\"); break; } else { last = middle - 1; } middle = (first + last)/2; } if ( first > last ) System.out.println(item + \" is not found.\ \"); } }
.
Once you have all the structures working as intended- it is time to co.docxfarrahkur54
Once you have all the structures working as intended, it is time to compare the
performances of the 2. Use runBenchmark() to start.
a. First, generate an increasing number (N) of random integers (1000, 5000, 10000,
50000, 75000, 100000, 500000 or as far as your computing power will let you)
i. Time and print how long it takes to insert the random integers into an initially
empty BST. Do not print the tree.
You can get a random list using the java class Random, located in
java.util.Random. To test the speed of the insertion algorithm, you should use
the System.currentTimeMillis() method, which returns a long that contains the
current time (in milliseconds). Call System.currentTimeMillis() before and after
the algorithm runs and subtract the two times. (Instant.now() is an alternative
way of recording the time.)
ii. Time and print how long it takes to insert the same random integers into an
initially empty AVL tree. Do not print the tree.
iii. If T(N) is the time function, how does the growth of TBST(N) compare with the
growth of TAVL(N)?
Plot a simple graph to of time against N for the two types of BSTs to visualize
your results.
b. Second, generate a list of k random integers. k is also some large value.
i. Time how long it takes to search your various N-node BSTs for all k random
integers. It does not matter whether the search succeeds.
ii. Time how long it takes to search your N-node AVL trees for the same k random
integers.
iii. Compare the growth rates of these two search time-functions with a graph the
same way you did in part a.
public class BinarySearchTree<AnyType extends Comparable<? super AnyType>> {
protected BinaryNode<AnyType> root;
public BinarySearchTree() {
root = null;
}
/**
* Insert into the tree; duplicates are ignored.
*
* @param x the item to insert.
* @param root
* @return
*/
protected BinaryNode<AnyType> insert(AnyType x, BinaryNode<AnyType> root) {
// If the root is null, we've reached an empty leaf node, so we create a new node
// with the value x and return it
if (root == null) {
return new BinaryNode<>(x, null, null);
}
// Compare the value of x to the value stored in the root node
int compareResult = x.compareTo(root.element);
// If x is less than the value stored in the root node, we insert it into the left subtree
if (compareResult < 0) {
root.left = insert(x, root.left);
}
// If x is greater than the value stored in the root node, we insert it into the right subtree
else if (compareResult > 0) {
root.right = insert(x, root.right);
}
// If x is equal to the value stored in the root node, we ignore it since the tree does not allow duplicates
return root;
}
/**
* Counts the number of leaf nodes in this tree.
*
* @param t The root of the tree.
* @return
*/
private int countLeafNodes(BinaryNode<AnyType> root) {
// If the root is null, it means the tree is empty, so we return 0
if (root == null) {
return 0;
}
// If the root has no children, it means it is a leaf node, so we return 1
if (root.left == .
Tree Traversals A tree traversal is the process of visiting.pdfajayadinathcomputers
Tree Traversals
A tree traversal is the process of "visiting" each node of a tree in some particular order. For a
binary search tree, we can talk about an inorder traversal and a preorder traversal. For this
assignment you are to implement both of these traversals in the code that was started in class.
File bstree.h contains the BSTree class that was developed during class (with the addition of
comments which were omitted by your instructor due to time constraints). The class contains two
inorder functions, one public and one private, and two preorder functions, also one public and one
private. As was the case with other functions implemented for this class, the public versions of
these functions simply call the private versions passing the root node (pointer) as a parameter.
The private versions carry out their actions on the subtree rooted at the given node.
The code provided in bstree.h is missing the implementations for the private inorder and preorder
functions. The coding part of this assignment is to implement these two functions.
When completed, the test program provided should produce the following output:
Values stored in the tree are:
bird
cat
deer
dog
giraffe
groundhog
horse
snake
turtle
The structure of the tree is as follows:
dog
-bird
--cat
---deer
-turtle
--giraffe
---snake
----groundhog
-----horse
Copied!
Written Part
In addition to the coding noted above, give an analysis of all public member functions of the class,
including all constructors, the destructor, and the overload of the assignment operator. For your
analysis you may assume a well-balanced tree (whereas a lopsided tree might lead to a different
analysis).
bstree.h
#pragma once
// A Binary Search Tree implementation.
template <typename T>
class BSTree {
private:
// A node in the tree. Each node has pointers to its left and right nodes
// as well as its parent. When a node is created, the parent and data item
// must be provided.
class node {
public:
T data;
node* left;
node* right;
node* parent;
node (const T& d, node* p) {
parent = p;
data = d;
left = right = nullptr;
}
};
// Pointer to the root node. Initially this is null for an empty tree.
node* root;
// Copy the subtree of another BSTree object into this object. Used by
// the copy constructor and assignment operator.
void copy (node* p) {
if (p) { // If p points to a node...
insert(p->data); // Insert data item
copy(p->left); // Copy the left subtree
copy(p->right); // Copy the right subtree
}
}
// Destroy a node and all nodes in both subtrees. Called by the
// destructor.
void destroy (node* p) {
if (p) { // If p is not null...
destroy(p->left); // Destroy the left subtree
destroy(p->right); // Destroy the right subtree
delete p; // Destroy the node
}
}
// Helper function to determine if a data value is contained in the tree.
// Takes the data value being searched and a pointer to the node in the
// tree. Returns pointer to node in which data item is found, a null
// pointer otherwise.
node* find (const T& .
4. The size of instructions can be fixed or variable. What are advant.pdfmumnesh
4. The size of instructions can be fixed or variable. What are advantage and disadvantage of
fixed compared to variable? point) eft 2 20 0 C-4131-28 Add suction 131-26 nvaction 125-2 PC
egister daiess mancion 120-16 date 1 regnter 2 nstructien 31-00 eg stcrs Read U ALLu dela tlata
dvts 02 rstend In the above figure (single-cycle implementation), current instruction is SW S1,
4(S2) (SW: Store Word; current addrss for this instruction is 100 in decimal; S1 and $2 are
initially 8). For redundancy, you should write \"X\" instead of 0 or . You should write the reason
for cach question as well. 5. What is the value of RegDst? (1 point) 6. What is the value of
RegWrite? (I point) 7. What is the value after sign-extension? 1 point) 8. What is the value of
MemRead? (1 point) 9. What is the value of MemtoReg? (1 point) In the above figure, current
instruction is ADDI $1. S2, #-1(which is minus l) (ADDI is ADD Immediate; current address for
this instruction s 100 in decimal and S2 are initially1). For redundancy, you should write “X\',
instead of 0 or 1 . You should write the reason for each question as well. 10. What is the value
(immediate value) of instruction [15-0)? Write the value in 6-bit binary (1 point) 11. What is the
value after sign extension? Write the value in 32-bit binary. (I point) 12. What is the value of
Reg Write? (1 point) 13. What is the value of MemtoReg? (1 point) 2/4
Solution
import java.util.AbstractSet; import java.util.Arrays; import java.util.Iterator; import
java.util.NoSuchElementException; /** * Implementation of an abstract set using an array-
based binary tree. This is * used to help teach binary tree\'s and will have more details explained
in * future lectures. * * @author William J. Collins * @author Matthew Hertz * @param
Data type (which must be Comparable) of the elements in this tree. */ public class
ArrayBinaryTree> extends AbstractSet { /** Entry in the data store where the root node can be
found. */ private static final int ROOT = 0; /** Array used to store the nodes which consist of
this binary tree. */ protected Node[] store; /** Number of elements within the tree. */
protected int size; /** * Initializes this ArrayBinaryTree object to be empty. This creates the
array * in which items will be stored. */ @SuppressWarnings(\"unchecked\") public
ArrayBinaryTree() { store = new Node[63]; size = 0; } /** * Initializes this
ArrayBinaryTree object to contain a shallow copy of a * specified ArrayBinaryTree object.
The worstTime(n) is O(n), where n is the * number of elements in the specified
ArrayBinaryTree object. * * @param otherTree The tree which will be copied to create our
new tree, */ @SuppressWarnings(\"unchecked\") public ArrayBinaryTree(ArrayBinaryTree
otherTree) { store = (Node[]) Arrays.copyOf(otherTree.store, otherTree.store.length); size =
otherTree.size; } public int countLeaves() { } /** * Returns the size of this
ArrayBinaryTree object. * * @return the size of this ArrayBinaryTree object. */
@Overrid.
JAVA - Design a data structure IntSet that can hold a set of integers-.docxolsenlinnea427
JAVA - Design a data structure IntSet that can hold a set of integers. Hide the private implementation: a Binary Search Tree of Integer objects. Provide the following public methods only.
• Constructor to make an empty set,
• Constructor to create a set by initializing the root,
• void add(int x) to add x if it is not present,
• void remove(int x) to remove x if it is present,
• void print() to print all the elements currently in the set,
• boolean contains(int x) to test whether x is present,
• IntSet copy() to create a new BTS as a copy of the current one.
Note that the root of the BST is a private data member and there is no need to define getRoot(), and setRoot() functions. All the above functions should be defined public and should call recursive private functions to do the task. e.g.
// remove
private Node recRemove(Node loc, int x) { // To do }
public void remove(int x) { root= recRemove(root, x) ; }
// contains
private boolean recContains(Node loc, int x) { // to do }
public boolean contains(int x) { return recContains(root, x) ; }
Complete the class IntSet by supplying the intersection and union functions. Use the same format as above i.e. each public function calls a private recursive function to do the task:
public IntSet union(IntSet other)
public IntSet intersection(IntSet other)
Solution
import java.util.Scanner; class BinarySearchExample { public static void main(String args[]) { int counter, num, item, array[], first, last, middle; //To capture user input Scanner input = new Scanner(System.in); System.out.println(\"Enter number of elements:\"); num = input.nextInt(); //Creating array to store the all the numbers array = new int[num]; System.out.println(\"Enter \" + num + \" integers\"); //Loop to store each numbers in array for (counter = 0; counter < num; counter++) array[counter] = input.nextInt(); System.out.println(\"Enter the search value:\"); item = input.nextInt(); first = 0; last = num - 1; middle = (first + last)/2; while( first <= last ) { if ( array[middle] < item ) first = middle + 1; else if ( array[middle] == item ) { System.out.println(item + \" found at location \" + (middle + 1) + \".\"); break; } else { last = middle - 1; } middle = (first + last)/2; } if ( first > last ) System.out.println(item + \" is not found.\ \"); } }
.
Write a C++ program that implements a binary search tree (BST) to man.pdfhardjasonoco14599
Write a C++ program that implements a binary search tree (BST) to manage a number of integer
items with different priorities. In order to do so. you will need to maintain a queue as an item in
the tree. Each queue item is an integer. All items in a given queue will have the same priority. As
a new item with a user-specified priority comes in, it should be enqueued in the queue with items
of that priority. A new queue may need to created in case a queue with that priority does not
exist. Use dynamic memory to manage nodes in the queue and BST. Implement the following:
Constructor. Destructor. Overloaded copy constructor. Overloaded assignment operator.
Overloaded \"==\" operator to check if two trees are equal. A tree t1 is equal to t2 if for every
queue in t1, a corresponding queue with the same priority exists in t2 with the same set of
elements (the order of the elements in the queue docs not matter). Overloaded \"
Solution
program using namespace std;
#define width_unit 5
class BStree
{
private:
class Node
{
public:
int data;
Node *left, *right;
Node(int d=0)
:data(d), left(NULL), right(NULL) {}
};
Node *root;
Node * trav(int, Node * &);
void chop(Node * N);
void copy(Node * N);
void print(ostream &, Node *, int) const;
void print(Node *, int) const;
public:
BStree(void);
~BStree(void);
bool find(int);
void insert(int);
void remove(int);
bool empty(void) const;
Tree(const BStree &);
const BStree & operator=(const BStree &);
friend ostream & operator<<(ostream &, const BStree &);
};
BStree::BStree(void)
{
root=NULL;
}
bool Tree::empty(void) const
{
return !root;
}
BStree::Node * BStree::trav(int foo, Node * & par)
{
Node * curr=root;
par=NULL;
while(curr && curr->data != foo)
{
par=curr;
if(foo < curr->data)
curr=curr->left;
else
curr=curr->right;
}
return curr;
}
bool BStree::find(int foo)
{
Node * par=NULL;
Node * curr=trav(foo, par);
return curr;
}
void BStree::insert(int foo)
{
Node * par=NULL;
Node * curr=trav(foo,par);
if(!curr)
{
curr= new Node(foo);
if(!par)
root=curr;
else if(foo < par->data)
par->left=curr;
else
par->right=curr;
}
}
void BStree::remove(const int foo)
{
Node * par=NULL;
Node * curr=trav(foo,par);
if(curr)
{
if(curr->left && curr->right)
{
Node * tmp=curr;
par=curr;
curr=curr->left;
while(curr->right)
{
par=curr;
curr=curr->right;
}
tmp->data=curr->data;
}
Node *tmp=(curr->left ? curr->left : curr->right);
if(!par)
root=tmp;
else if(par->data < curr->data)
par->right=tmp;
else
par->left=tmp;
delete curr;
}
}
void BStree::chop(Node *N)
{
if(N)
{
chop(N->left);
chop(N->right);
delete N;
}
}
BStree::~BStree(void)
{
chop(root);
}
BStree::BStree(const BStree & T)
{
root=NULL;
copy(T.root);
}
void BStree::copy(Node * N)
{
if(N)
{
insert(N->data);
copy(N->left);
copy(N->right);
}
}
const BStree & BStree::operator=(const BStree & T)
{
if(this != &T)
{
chop(root);
root=NULL;
copy(T.root);
}
return *this;
}
void BStree::print(ostream & ost, Node * curr, int level) const
{
if(curr)
{
print(ost,curr->right,level+1);
ost<data<le.
Write a program that accepts an arithmetic expression of unsigned in.pdfJUSTSTYLISH3B2MOHALI
Write a program that accepts an arithmetic expression of unsigned integers in postfix notation
and builds the arithmetic expression tree that represents that expression. From that tree, the
corresponding fully parenthesized infix expression should be displayed and a file should be
generated that contains the three address format instructions. This topic is discussed in the week
4 reading in module 2, section II-B. The main class should create the GUI shown below:
Pressing the Construct Tree button should cause the tree to be constructed and using that tree, the
corresponding infix expression should be displayed and the three address instruction file should
be generated. The postfix expression input should not be required to have spaces between every
token. Note in the above example that 9+- are not separated by spaces. The above example
should produce the following output file containing the three address instructions:
Add R0 5 9
Sub R1 3
R0 Mul R2 2 3
Div R3 R1 R2
Inheritance should be used to define the arithmetic expression tree. At a minimum, it should
involve three classes: an abstract class for the tree nodes and two derived classes, one for
operand nodes and another for operator nodes. Other classes should be included as needed to
accomplish good object-oriented design. All instance data must be declared as private.
You may assume that the expression is syntactically correct with regard to the order of operators
and operands, but you should check for invalid tokens, such as characters that are not valid
operators or operands such as 2a, which are not valid integers. If an invalid token is detected a
RuntimeException should be thrown and caught by the main class and an appropriate error
message should be displayed. Three Adddress Generator Enter Postfix Expression 359 2 3
Construct Tree Infix Expression ((3-(5 9))/ (2* 3
Solution
#include
#include
#include
#include
#include
struct TREE //Structure to represent a tree
{
char data;
struct TREE *right,*left,*root;
};
typedef TREE tree; /* Stack Using Linked List */
struct Stack //Structure to represent Stack
{
struct TREE *data;
struct Stack *next,*head,*top; //Pointers to next node,head and top
};
typedef struct Stack node;
node *Nw; //Global Variable to represent node
void initialize(node *&n)
{
n = new node;
n -> next = n -> head = n -> top = NULL;
}
void create(node *n)
{
Nw = new node; //Create a new node
Nw -> next = NULL; //Initialize next pointer field
if(n -> head == NULL) //if first node
{
n -> head = Nw; //Initialize head
n -> top = Nw; //Update top
}
}
void push(node *n,tree *ITEM)
{
node *temp = n -> head;
if(n -> head == NULL) //if First Item is Pushed to Stack
{
create(n); //Create a Node
n -> head -> data = ITEM; //Insert Item to head of List
n -> head = Nw;
return; //Exit from Function
}
create(n); //Create a new Node
Nw -> data = ITEM; //Insert Item
while(temp -> next != NULL)
temp = temp -> next; //Go to Last Node
temp -> next = Nw; //Point New node
n -> top = Nw; //Upda.
Running Head: Discussion Board 1
Discussion Board 3
Discussion Board
Student’s Name
Institution Affiliation
My topics for this discussion will lean on the immigration and the plight of immigrants. This is a subject that will bring a good platform to form an informative as well as persuasive speech. I will specifically address the value of policy making in the management of immigration trends that are increasing in the USA as well as western countries (Zatz, & Rodriguez, 2015). The topic will be “Do illegal immigrants deserve a hearing in the countries they seek asylum or they should just be deported impartially?” I think this is a contentious issue in the world today.
There are many policies that have been established by various international organizations such as UN in regard to Immigration. The underlying issues in this matter still remain dormant and unresolved. The fundamental question of concern is addressing the parties that should be concerned with this matter. I will be addressing the international community as my audience, particularly the UN, countries. The speech will also include recommendations that will be suggested for handling of the matter. It will also give a discourse of the current situation in different parts of the world such as USA and Europe. This will paint a picture of the dire need of the situation and the dangers that immigrants are facing every day. It will also address the plight of illegal immigrants who I will argue that they deserve humanly just and fair treatment whenever they are met by the hand of the law. The speech is intended to bring an evaluation of the essence of humanity in considering one another and building bridges that alleviate instead of perpetuating human suffering in the world.
References
Zatz, M. S., & Rodriguez, N. (2015). Dreams and nightmares: Immigration policy, youth, and families. University of California Press.
ASS12/assg-12.cppASS12/assg-12.cpp/**
*
* @description Assignment 12 Binary Search Trees
*/
#include<cassert>
#include<iostream>
#include"BinaryTree.hpp"
usingnamespace std;
/** main
* The main entry point for this program. Execution of this program
* will begin with this main function.
*
* @param argc The command line argument count which is the number of
* command line arguments provided by user when they started
* the program.
* @param argv The command line arguments, an array of character
* arrays.
*
* @returns An int value indicating program exit status. Usually 0
* is returned to indicate normal exit and a non-zero value
* is returned to indicate an error condition.
*/
int main(int argc,char** argv)
{
// -----------------------------------------------------------------------
...
Array is a container which can hold a fix number of items and these items should be of the same type. Most of the data structures make use of arrays to implement their algorithms. Following are the important terms to understand the concept of array.
Please help solve this in C++ So the program is working fin.pdfankit11134
Please help solve this in C++. So the program is working fine but when submitting it, it gives me a
code -11, and I believe the problem is that after inserting the numbers it removes them one by one
until the last in the list, and when it tries to remove the last number in the list that is when it
counters the problem. Below is the full code but you just need to change something in the
SortedNumberList.h file under the bool remove function.
4.18 LAB: Sorted number list implementation with linked lists Step 1: Inspect the Node.h file
Inspect the class declaration for a doubly-linked list node in Node.h. Access Node.h by clicking on
the orange arrow next to main.cpp at the top of the coding window. The Node class has three
member variables: - a double data value, - a pointer to the next node, and - a pointer to the
previous node. Each member variable is protected. So code outside of the class must use the
provided getter and setter member functions to get or set a member variable. Node.h is read only,
since no changes are required. Step 2: Implement the Insert() member function A class for a
sorted, doubly-linked list is declared in SortedNumberList.h. Implement the SortedNumberList
class's Insert() member function. The function must create a new node with the parameter value,
then insert the node into the proper sorted position in the linked list. Ex: Suppose a
SortedNumberList's current list is 2347.2586, then Insert(33.5) is called. A new node with data
value 33.5 is created and inserted between 23 and 47.25, thus preserving the list's sorted order
and yielding: 2335.547.2586Step 3: Test in develop mode Code in main() takes a space-
separated list of numbers and inserts each into a SortedNumberList. The list is displayed after
each insertion. Ex: If input is 77154263.5 then output is: List after inserting 77 : 77 List after
inserting 15 : 1577 List after inserting -42 : -421577 List after inserting 63.5: -421563.577 Try
various program inputs, ensuring that each outputs a sorted list. Step 4: Implement the Remove()
member function Implement the SortedNumberList class's Remove(0 member function. The
function takes a parameter for the number to be removed from the list. If the number does not
exist in the list, the list is not changed and false is returned. Otherwise, the first instance of the
number is removed from the list and true is returned. Uncomment the commented-out part in
main() that reads a second input line and removes numbers from the list. Test in develop mode to
ensure that insertion and removal both work properly, then submit code for grading. Ex: If input is
841972841961 then output is: List after inserting 84: 84 List after inserting 72 : 7284 List after
inserting 19: 1972 84 List after inserting 61: 1961 : 72 8 List after removing 19: 6172 84 List after
removing 84: 6172Current file: main.cpp - // Insert each value and show the sorted List's contents
after each insertion sortedNumberList list; for (auto term : terms) { doubl.
Given the following ADT definition of a stack to use stack .docxshericehewat
Given the following ADT definition of a stack to use:
/** stack (base class)
* The basic definition of the Stack Abstract Data Type (ADT)
* and stack operations. All declared functions here are
* virtual, they must be implemented by concrete derived
* classes.
*/
template <class T>
class Stack
{
public:
/** clear
* Method to clear out or empty any items on stack,
* put stack back to empty state.
* Postcondition: Stack is empty.
*/
virtual void clear() = 0;
/** isEmpty
* Function to determine whether the stack is empty. Needed
* because it is undefined to pop from empty stack. This
* function will not change the state of the stack (const).
*
* @returns bool true if stack is empty, false otherwise.
*/
virtual bool isEmpty() const = 0;
/** push
* Add a new item onto top of stack.
*
* @param newItem The item of template type T to push on top of
* the current stack.
*/
virtual void push(const T& newItem) = 0;
/** top
* Return the top item from the stack. Note in this ADT, peeking
* at the top item does not remove the top item. Some ADT combine
* top() and pop() as one operation. It is undefined to try and
* peek at the top item of an empty stack. Derived classes should
* throw an exception if this is attempted.
*
* @returns T Returns the top item from stack.
*/
virtual T top() const = 0;
/** pop
* Remove the item from the top of the stack. It is undefined what
* it means to try and pop from an empty stack. Derived classes should
* throw an exception if pop() from empty is attempted.
*/
virtual void pop() = 0;
/** size
* Accessor method to provide the current size of the stack.
*
* @returns int The current size (number of items) on the stack.
*/
virtual int size() const = 0;
};
perform the following tasks by writing code that uses a stack to accomplish the task. You will
need to create a stack of the needed type, then use the methods of the stack abstraction (push,
top, pop, etc.) to solve the given task asked for.
Question 7 (5 points)
Given a stack of integers, calculate the sum of the integer values. Also, the stack should still be
unchanged after you have calculated the sum Hint: take the items off the stack to sum them up
and keep them on a second temporary stack so you can put them all back on after you have
calculated the sum.
ANSWER FOR NUMBER 7:
int sumStackOfIntegers(Stack<int> currentStack) {
Stack<int> tempStack;
int sum = 0;
while(!currentStack.isEmpty()) {
int temp = currentStack.top();
tempStack.push(temp);
currentStack.pop();
sum += temp;
}
while(!tempStack.isEmpty()) {
int temp = tempStack.top();
currentStack.push(temp);
tempStack.pop();
}
return sum;
}
Stack Implementation
Given the following linked list implementation of a Stack ADT (this is the same implementation
you used in Assignment 10), add the asked for additional member methods to the linked list stack
implementation.
/** Node
* A basic node contaning an item and a link to t ...
Use the following data set that compares age to average years lef.docxdickonsondorris
Use the following data set that compares age to average "years left to live" to answer the following questions.
Age 10 20 30 40 50 60 70 80 90 100
Years to live 59.2 49.6 40.7 31.9 24.0 17.2 11.6 7.2 4 .4 2.8
a) Show the scatterplot for this data with the least squares regression line. Find R^2. How much of the variation is explained by the regression line?
b) Experiment with the non-linear regressions available on the calculator. Which seem to fit? Show the scatterplot with three different regression curves from the calculator. Label each equation, as well as the applicable R^2.
c) Choose a regression equation to predict how many "years left" a person has if he is now 101 years old. Can he count on celebrating Christmas 2015?
InfoTest.javaInfoTest.javapackage assignment1;
importstatic org.junit.Assert.*;
import org.junit.Test;
publicclassInfoTest{
@Test
publicvoid testInfo(){
Info tempInfo =newInfo();
assertNotNull(tempInfo.tmp);
}
@Test
publicvoid testInsert(){
Info tempInfo =newInfo();
// Insert into an empty list
tempInfo.insert(30);
assertEquals(30, tempInfo.get(0));
// Insert an item to be placed at the beginning of the list
tempInfo.insert(4);
assertEquals(4, tempInfo.get(0));
assertEquals(30, tempInfo.get(1));
// Insert an item to be placed at the end of the list
tempInfo.insert(20);
assertEquals(20, tempInfo.get(1));
assertEquals(30, tempInfo.get(2));
// Insert an which already exists
tempInfo.insert(20);
assertEquals(4, tempInfo.get(0));
assertEquals(20, tempInfo.get(1));
assertEquals(30, tempInfo.get(2));
}
@Test
publicvoid testDelete(){
Info tempInfo =newInfo();
tempInfo.insert(15);
tempInfo.insert(5);
tempInfo.insert(10);
// delete from the middle
tempInfo.delete(10);
assertEquals(5, tempInfo.get(0));
assertEquals(15, tempInfo.get(1));
// delete from the beginning
tempInfo.insert(10);
tempInfo.delete(5);
assertEquals(10, tempInfo.get(0));
assertEquals(15, tempInfo.get(1));
// delete from the end
tempInfo.insert(5);
tempInfo.delete(15);
assertEquals(5, tempInfo.get(0));
assertEquals(10, tempInfo.get(1));
// delete something that does not exist
tempInfo.insert(15);
tempInfo.delete(7);
assertEquals(5, tempInfo.get(0));
assertEquals(10, tempInfo.get(1));
assertEquals(15, tempInfo.get(1));
}
@Test
publicvoid testGet(){
Info tempInfo =newInfo();
tempInfo.insert(15);
tempInfo.insert(5);
tempInfo.insert(10);
// get items at the beginning, middle, and end of the list
assertEquals(5, tempInfo.get(0));
assertEquals(10, tempInfo.get(1));
assertEquals(15, tempInfo.get(2));
// get an unexisting item
assertNull(tempInfo.get(3));
}
@Test
publicvoid testCount(){
Info tempInfo =newInfo();
/ ...
Assg 12 Binary Search TreesCOSC 2336 Spring 2019April.docxfestockton
Assg 12: Binary Search Trees
COSC 2336 Spring 2019
April 10, 2019
Dates:
Due: Sunday April 21, by Midnight
Objectives
� Practice recursive algorithms
� Learn how to construct a binary tree using pointers/linked nodes
� Learn about binary tree traversal
Description
In this assignment you will be given the beginning of a BinaryTree imple-
mentation using linked nodes via pointers. You will be implementing some
of the basic function of a BinaryTree abstract data type. The abstraction
we are using for the BinaryTreeNode and the BinaryTree are similar to
the Sha�er BSTNode (pg. 156,161) and the BST abstract class and linked
pointer implementation (Sha�er pg. 171), but we will de�ne our own version
and simplify some of the functions and interface.
You have been given a BinaryTree.[cpp|hpp] �le that de�nes the BinaryTreeNode
structure and BinaryTree class. This class is current not templatized, the
constructed trees only hold items of simple type int (one of the extra credit
opportunities suggests you templatize your resulting class). The BinaryTree
has a constructor, and you have been provided a tostring() method and
an overloaded operator�() so that you can display the current contents of
the tree.
For this assignment you need to perform the following tasks.
1
1. In order to test your class, we �rst have to get a working capability to
insert new items into the BinaryTree, which isn't the simplest task to
start with, but we can't really test others until we can add new items.
For many of the functions in this assignment, you will be required to
implement them using a recursive function. Thus many of the func-
tions for your BinaryTree will have a public function that asks as the
interface that is called by users of the BinaryTree, and a private ver-
sion that actually does the work using a recursive algorithm. I will
give you the signature you need for the insert() functions:
class BinaryTree
{
private:
BinaryTreeNode* insert(BinaryTreeNode* node, const int item);
public:
void insert(const int item);
}
Lets start �rt with the public insert() function. This function is the
public interface to insert a new item into the tree. Since we are only
implementing a tree of int items, you simply pass in the int value that
is to be inserted. This function basically only needs to call the private
insert() function, passing in the current root of the tree as the �rst
parameter, and the item to be inserted as the second parameter. Notice
that the private insert() returns a pointer to a BinaryTreeNode.
The private insert() function is a recursive function. The base case
is simple. If the node you pass in is NULL, then that means you have
found the location where a new node should be created and inserted.
So for the base case, when node is NULL you should dynamically create
a new BinaryTreeNode item, assign the item and make sure that the
left and right pointers are initialized to NULL. When you create a new
node like this, you should retu ...
MAINCPP include ltiostreamgt include ltstringgt u.pdfadityastores21
MAIN.CPP
#include <iostream>
#include <string>
using namespace std;
#include "bstree.h"
// Prints a single string, used by FSTree::inorder to print all
// values in the tree in correct order.
void print_string (string s) { cout << s << endl; }
// Prints a single string preceeded by a number of hyphens, used by
// BSTree::preorder to print a visual representation of the tree.
void print_string_depth (string s, int n) {
for (int i = 0; i < n; i++)
cout << '-';
cout << s << endl;
}
int main () {
// Create a binary search tree.
BSTree<string> t;
// Insert some strings for testing.
t.insert("dog");
t.insert("bird");
t.insert("cat");
t.insert("turtle");
t.insert("giraffe");
t.insert("snake");
t.insert("deer");
t.insert("groundhog");
t.insert("horse");
// Output the values stored in the tree.
cout << "Values stored in the tree are:n";
t.inorder(print_string);
cout << "n";
cout << "The structure of the tree is as follows:n";
t.preorder(print_string_depth);
cout << "n";
}
BSTREE.h
#pragma once
// A Binary Search Tree implementation.
template <typename T>
class BSTree {
private:
// A node in the tree. Each node has pointers to its left and right nodes
// as well as its parent. When a node is created, the parent and data item
// must be provided.
class node {
public:
T data;
node* left;
node* right;
node* parent;
node (const T& d, node* p) {
parent = p;
data = d;
left = right = nullptr;
}
};
// Pointer to the root node. Initially this is null for an empty tree.
node* root;
// Copy the subtree of another BSTree object into this object. Used by
// the copy constructor and assignment operator.
void copy (node* p) {
if (p) { // If p points to a node...
insert(p->data); // Insert data item
copy(p->left); // Copy the left subtree
copy(p->right); // Copy the right subtree
}
}
// Destroy a node and all nodes in both subtrees. Called by the
// destructor.
void destroy (node* p) {
if (p) { // If p is not null...
destroy(p->left); // Destroy the left subtree
destroy(p->right); // Destroy the right subtree
delete p; // Destroy the node
}
}
// Helper function to determine if a data value is contained in the tree.
// Takes the data value being searched and a pointer to the node in the
// tree. Returns pointer to node in which data item is found, a null
// pointer otherwise.
node* find (const T& d, node* p) const {
// Given: p is a pointer to an existing node
if (d == p->data) // Is this the value we're looking for?
return p;
if (d < p->data) // Check left side, if null then not found
return p->left ? find(d, p->left) : nullptr;
return p->right ? find(d, p->right) : nullptr; // Check right side...
}
// Helper function to insert a data item into the tree. Takes the data
// and a pointer to a node in the tree. Recursively decends down the tree
// until position were insertion should take place is found.
void insert (const T& d, node* p) {
// Given: p is a pointer to an existing node (root of a subtree)
if (d < p->data) { // Insert into left subtree?
if (p->left) // Left.
Describe a data structure to represent sets of elements (each element.pdfrajeshjain2109
Describe a data structure to represent sets of elements (each element with a unique key) that
would support the following operations: insert(x, A) - insert an element x into A (assume the key
of x is not in .4 yet) count (A, k) - return the number of elements in A with key at least k.
Solution
we can use Hashset for this.a simple code in hashset is given below
public class MyNode
{
...
}
public class MyDataStructure
{
private HashSet nodes = new HashSet();
///
/// Inserts an element to this data structure.
/// If the element already exists, returns false.
/// Complexity is averaged O(1).
///
public bool Add(MyNode node)
{
return node != null && this.nodes.Add(node);
}
///
/// Removes a random element from the data structure.
/// Returns the element if an element was found.
/// Returns null if the data structure is empty.
/// Complexity is averaged O(1).
///
public MyNode Pop()
{
// This loop can execute 1 or 0 times.
foreach (MyNode node in nodes)
{
this.nodes.Remove(node);
return node;
}
return null;
}
}
the unique key can also be achieved using dictioneries
hence code for this is given below:
public class FixedIntDictionary
{
// Our internal node structure.
// We use structs instead of objects to not add pressure to the garbage collector.
// We mantains our own way to manage garbage through the use of a free list.
private struct Entry
{
// The key of the node
internal int Key;
// Next index in pEntries array.
// This field is both used in the free list, if node was removed
// or in the table, if node was inserted.
// -1 means null.
internal int Next;
// The value of the node.
internal T Value;
}
// The actual hash table. Contains indices to pEntries array.
// The hash table can be seen as an array of singlt linked list.
// We store indices to pEntries array instead of objects for performance
// and to avoid pressure to the garbage collector.
// An index -1 means null.
private int[] pBuckets;
// This array contains the memory for the nodes of the dictionary.
private Entry[] pEntries;
// This is the first node of a singly linked list of free nodes.
// This data structure is called the FreeList and we use it to
// reuse removed nodes instead of allocating new ones.
private int pFirstFreeEntry;
// Contains simply the number of items in this dictionary.
private int pCount;
// Contains the number of used entries (both in the dictionary or in the free list) in pEntries
array.
// This field is going only to grow with insertions.
private int pEntriesCount;
///
/// Creates a new FixedIntDictionary.
/// tableBucketsCount should be a prime number
/// greater than the number of items that this
/// dictionary should store.
/// The performance of this hash table will be very bad
/// if you don\'t follow this rule!
///
public FixedIntDictionary(int tableBucketsCount)
{
// Our free list is initially empty.
this.pFirstFreeEntry = -1;
// Initializes the entries array with a minimal amount of items.
this.pEntries = new Entry[8];
// Allocate buckets and initial.
Assg 12 Binary Search Trees COSC 2336assg-12.cppAssg 12 Binary .docxfestockton
Assg 12 Binary Search Trees COSC 2336/assg-12.cppAssg 12 Binary Search Trees COSC 2336/assg-12.cpp/**
* @author Jane Programmer
* @cwid 123 45 678
* @class COSC 2336, Spring 2019
* @ide Visual Studio Community 2017
* @date April 8, 2019
* @assg Assignment 12
*
* @description Assignment 12 Binary Search Trees
*/
#include<cassert>
#include<iostream>
#include"BinaryTree.hpp"
usingnamespace std;
/** main
* The main entry point for this program. Execution of this program
* will begin with this main function.
*
* @param argc The command line argument count which is the number of
* command line arguments provided by user when they started
* the program.
* @param argv The command line arguments, an array of character
* arrays.
*
* @returns An int value indicating program exit status. Usually 0
* is returned to indicate normal exit and a non-zero value
* is returned to indicate an error condition.
*/
int main(int argc,char** argv)
{
// -----------------------------------------------------------------------
cout <<"--------------- testing BinaryTree construction ----------------"<< endl;
BinaryTree t;
cout <<"<constructor> Size of new empty tree: "<< t.size()<< endl;
cout << t << endl;
assert(t.size()==0);
cout << endl;
// -----------------------------------------------------------------------
cout <<"--------------- testing BinaryTree insertion -------------------"<< endl;
//t.insert(10);
//cout << "<insert> Inserted into empty tree, size: " << t.size() << endl;
//cout << t << endl;
//assert(t.size() == 1);
//t.insert(3);
//t.insert(7);
//t.insert(12);
//t.insert(15);
//t.insert(2);
//cout << "<insert> inserted 5 more items, size: " << t.size() << endl;
//cout << t << endl;
//assert(t.size() == 6);
cout << endl;
// -----------------------------------------------------------------------
cout <<"--------------- testing BinaryTree height -------------------"<< endl;
//cout << "<height> Current tree height: " << t.height() << endl;
//assert(t.height() == 3);
// increase height by 2
//t.insert(4);
//t.insert(5);
//cout << "<height> after inserting nodes, height: " << t.height()
// << " size: " << t.size() << endl;
//cout << t << endl;
//assert(t.height() == 5);
//assert(t.size() == 8);
cout << endl;
// -----------------------------------------------------------------------
cout <<"--------------- testing BinaryTree clear -------------------"<< endl;
//t.clear();
//cout << "<clear> after clearing tree, height: " << t.height()
// << " size: " << t.size() << endl;
//cout << t << endl;
//assert(t.size() == 0);
//assert(t.height() == 0);
cout << endl;
// return 0 to indicate successful completion
return0;
}
Assg 12 Binary Search Trees COSC 2336/assg-12.pdf
Assg 12: Binary Search Trees
COSC 2336 Spring 2019
April 10, 2019
Dates:
Due: Sunday April 21, by Midnight
Objectives
� Practice recursive algorithms
� Learn how to construct a binary tree usi ...
AvlTree.h
#ifndef AVL_TREE_H
#define AVL_TREE_H
#include "dsexceptions.h"
#include <iostream> // For NULL
#include <queue> // For level order printout
#include <vector>
#include <algorithm> // For max() function
using namespace std;
// AvlTree class
//
// CONSTRUCTION: with ITEM_NOT_FOUND object used to signal failed finds
//
// ******************PUBLIC OPERATIONS*********************
// Programming Assignment Part I
// bool empty( ) --> Test for empty tree @ root
// int size( ) --> Quantity of elements in tree
// int height( ) --> Height of the tree (null == -1)
// void insert( x ) --> Insert x
// void insert( vector<T> ) --> Insert whole vector of values
// void remove( x ) --> Remove x (unimplemented)
// bool contains( x ) --> Return true if x is present
// Comparable findMin( ) --> Return smallest item
// Comparable findMax( ) --> Return largest item
// boolean isEmpty( ) --> Return true if empty; else false
// void printTree( ) --> Print tree in sorted (in) order
// void printPreOrder( ) --> Print tree in pre order
// void printPostOrder( ) --> Print tree in post order
// void printInOrder( ) --> Print tree in *in* order
// Programming Assignment Part II (microassignment)
// void makeEmpty( ) --> Remove and delete all items
// void ~AvlTree( ) --> Big Five Destructor
// AvlTree(const AvlTree &other) --> BigFive Copy Constructor
// AvlTree(const AvlTree &&other) --> BigFive Move Constructor
// AvlTree &operator= ( AvlTree & other ) --> Big Five Copy *assignment* operator
// AvlTree &operator= ( AvlTree && other ) --> Big Five Move *assignment* operator
// void printLevelOrder( ) --> Print tree in LEVEL order :-)
// ******************ERRORS********************************
// Throws UnderflowException as warranted
template <typename Comparable>
class AvlTree
{
public:
/**
* Basic constructor for an empty tree
*/
AvlTree( ) : root( NULL )
{
//cout << " [d] AvlTree constructor called. " << endl;
}
/**
* Vector of data initializer (needed for move= operator rvalue)
*/
AvlTree( vector<Comparable> vals ) : root( NULL )
{
insert(vals);
}
//*******************************************************************************************
// START AVL TREES PART II - TODO: Implement
// Other functions to look for include: clone, makeEmpty, printLevelOrder
/**
* Destroy contents of the AvlTree object - Big Five Destructor
*/
~AvlTree( )
{
//cout << " [d] AvlTree Destructor called. " << endl;
// Empty out the AVL Tree and destroy all nodes (makeEmpty?)
}
/**
* Copy other to new object - Big Five Copy Constructor
*/
AvlTree( const AvlTree &other ) : root( NULL )
{
cout << " [d] Copy Constructor Called." << endl;
// Copy contents of other to ourselves (maybe clone?)
// Get a deep copy of other's tree
}
/* ...
(Parent reference for BST) Redefine TreeNode by adding a reference to.pdfarihantelehyb
(Parent reference for BST) Redefine TreeNode by adding a reference to a node\'s parent, as
shown below\': Reimplement the insert and delete methods in the BST class to update the parent
for each node in the tree. Add the following new method in BST:/** Returns the node for the
specified element. * Returns null if the element is not in the tree. */private TreeNode getNode(E
element)/** Returns true if the node for the element is a leaf */private boolean isLeaf(E
element)/** Returns the path of elements from the specified element * to the root in an array
list. */public ArrayList getPath(E e) Write a test program that prompts the user to enter 10
integers, adds them to the tree, deletes the first integer from the tree, and displays the paths for
all leaf nodes. Here is a sample run:
Solution
#include
#include
void swap(char *x, char *y)
{
char temp;
temp = *x;
*x = *y;
*y = temp;
void permute(char *a, int l, int r)
{
int i;
if (l == r)
printf(\"%s\ \", a);
else
{
for (i = l; i <= r; i++)
{
swap((a+l), (a+i));
permute(a, l+1, r);
swap((a+l), (a+i)); //backtrack
}
}
}
int main()
{
char str[] = \"ABC\";
int n = strlen(str);
permute(str, 0, n-1);
return 0;
}
part ii radix sort:
c++
#include
using namespace std;
int getMax(int arr[], int n)
{
int mx = arr[0];
for (int i = 1; i < n; i++)
if (arr[i] > mx)
mx = arr[i];
return main()
void countSort(int arr[], int n, int exp
for (i = 0; i < n; i++)
count[ (arr[i]/exp)%10 ]++;
for (i = 1; i < 10; i++)
count[i] += count[i - 1];
for (i = n - 1; i >= 0; i--)
{
output[count[ (arr[i]/exp)%10 ] - 1] = arr[i];
count[ (arr[i]/exp)%10 ]--;
}
for (i = 0; i < n; i++)
arr[i] = output[i];
}
adixsort(int arr[], int n)
{
int m = getMax(arr, n);
for (int exp = 1; m/exp > 0; exp *= 10)
countSort(arr, n, exp);
}
void print(int arr[], int n)
{
for (int i = 0; i < n; i++)
cout << arr[i] << \" \";
}
int main()
{
int arr[] = {170, 45, 75, 90, 802, 24, 2, 66};
int n = sizeof(arr)/sizeof(arr[0]);
radixsort(arr, n);
print(arr, n);
return 0;
}
java:
import java.io.*;
import java.util.*;
class Radix {
static int getMax(int arr[], int n)
{
int mx = arr[0];
for (int i = 1; i < n; i++)
if (arr[i] > mx)
mx = arr[i];
return mx;
}
static void countSort(int arr[], int n, int exp)
{
int output[] = new int[n]; // output array
int i;
int count[] = new int[10];
Arrays.fill(count,0);
for (i = 0; i < n; i++)
count[ (arr[i]/exp)%10 ]++;
for (i = 1; i < 10; i++)
count[i] += count[i - 1];
for (i = n - 1; i >= 0; i--)
{
output[count[ (arr[i]/exp)%10 ] - 1] = arr[i];
count[ (arr[i]/exp)%10 ]--;
}
for (i = 0; i < n; i++)
arr[i] = output[i];
}
static void radixsort(int arr[], int n)
{
int m = getMax(arr, n);
for (int exp = 1; m/exp > 0; exp *= 10)
countSort(arr, n, exp);
}
static void print(int arr[], int n)
{
for (int i=0; i
#include
void swap(char *x, char *y)
{
char temp;
temp = *x;
*x = *y;
*y = temp;
void permute(char *a, int l, int r)
{
int i;
if (l == r)
printf(\"%s\ \", a);
else
{
for (i = l; i <= r; i++)
{
swap((a+l), (a+i));
permute(a, l+1, .
ReversePoem.java ---------------------------------- public cl.pdfravikapoorindia
ReversePoem.java :-
---------------------------------
public class ReversePoem {
/*This programs has you display a pessimistic poem from a list of phrases*/
// and then reverse the phrases to find another more optimistic poem.
public static void main(String[] args) throws Exception
{
//Queue object
MyQueue queue = new MyQueue<>();
//Stack object
MyStack stack = new MyStack<>();
//String buffer to apppend all Strings
StringBuffer sb = new StringBuffer();
// Create a single String object from the 16 Strings below
String set1 = \"I am part of a lost generation#and I refuse to believe that#\";
sb.append(set1);
String set2 = \"I can change the world#I realize this may be a shock but#\";
sb.append(set2);
String set3 = \"\'Happiness comes from within\'#is a lie, and#\";
sb.append(set3);
String set4 = \"\'Money will make me happy\'#So in 30 years I will tell my children#\";
sb.append(set4);
String set5 = \"they are not the most important thing in my life#\";
sb.append(set5);
String set6 = \"My employer will know that#I have my priorities straight because#\";
sb.append(set6);
String set7 = \"work#is more important than#family#I tell you this#\";
sb.append(set7);
String set8 = \"Once upon a time#Families stayed together#\";
sb.append(set8);
String set9 = \"but this will not be true in my era#\";
sb.append(set9);
String set10 = \"This is a quick fix society#Experts tell me#\";
sb.append(set10);
String set11 = \"30 years from now, I will be celebrating the 10th anniversary of my
divorce#\";
sb.append(set11);
String set12 = \"I do not concede that#I will live in a country of my own making#\";
sb.append(set12);
String set13 = \"In the future#Environmental destruction will be the norm#\";
sb.append(set13);
String set14 = \"No longer can it be said that#My peers and I care about this earth#\";
sb.append(set14);
String set15 = \"It will be evident that#My generation is apathetic and lethargic#\";
sb.append(set15);
String set16 = \"It is foolish to presume that#There is hope#\";
sb.append(set16);
String finalString = sb.toString();
String itmes[] = finalString.split(\"#\");
System.out.println(\"========== Original Phrase ==============\");
for(int i = 0 ; i < itmes.length;i++){
queue.enqueue(itmes[i]);
System.out.println(itmes[i]);
}
for(int i = 0 ; i < itmes.length;i++){
stack.push(queue.dequeue());
}
System.out.println(\"========== Reverse Phrase ==============\");
for(int i = 0 ; i < itmes.length;i++){
System.out.println(stack.pop());
}
/* You are given a list of phrases in Strings; the phrases
are separated by pound signs: \'#\':
1. Create a single String object from this list.
2. Then, split the String of phrases into an array of
phrases using the String split method.
3. Display a poem by walking through the array and
displaying each phrase one per line.
4. And, at the same time, place each phrase on a
MyQueue object using only the enqueue method.
5. After all the phrases have been placed on the queue,
transfer the phrases from the MyQueue object to a
MyS.
On the code which has a class in which I implementing a binary tree .pdfwasemanivytreenrco51
On the code which has a class in which I implementing a binary tree using an array. This array,
named store, stores Node in entries corresponding to
nodes in the tree and null if the node does not exist. Complete the countLeavesmethod so that it
returns the number of leaves in this tree.
Code:
Solution
import java.util.AbstractSet; import java.util.Arrays; import java.util.Iterator; import
java.util.NoSuchElementException; /** * Implementation of an abstract set using an array-
based binary tree. This is * used to help teach binary tree\'s and will have more details explained
in * future lectures. * * @author William J. Collins * @author Matthew Hertz * @param
Data type (which must be Comparable) of the elements in this tree. */ public class
ArrayBinaryTree> extends AbstractSet { /** Entry in the data store where the root node can be
found. */ private static final int ROOT = 0; /** Array used to store the nodes which consist of
this binary tree. */ protected Node[] store; /** Number of elements within the tree. */
protected int size; /** * Initializes this ArrayBinaryTree object to be empty. This creates the
array * in which items will be stored. */ @SuppressWarnings(\"unchecked\") public
ArrayBinaryTree() { store = new Node[63]; size = 0; } /** * Initializes this
ArrayBinaryTree object to contain a shallow copy of a * specified ArrayBinaryTree object.
The worstTime(n) is O(n), where n is the * number of elements in the specified
ArrayBinaryTree object. * * @param otherTree The tree which will be copied to create our
new tree, */ @SuppressWarnings(\"unchecked\") public ArrayBinaryTree(ArrayBinaryTree
otherTree) { store = (Node[]) Arrays.copyOf(otherTree.store, otherTree.store.length); size =
otherTree.size; } public int countLeaves() { } /** * Returns the size of this
ArrayBinaryTree object. * * @return the size of this ArrayBinaryTree object. */
@Override public int size() { return size; } /** * Returns an iterator that will return the
elements in this ArrayBinaryTree, * but without any specific ordering. * * @return Iterator
positioned at the smallest element in this ArrayBinaryTree * object. */ @Override
public Iterator iterator() { return new ArrayTreeIterator(); } /** * Determines if there is at
least one element in this ArrayBinaryTree object * that equals a specified element. The
worstTime(n) is O(n) and * averageTime(n) is O(log n). * * @param obj - the element
sought in this ArrayBinaryTree object. * @return true - if there is an element in this
ArrayBinaryTree object that * equals obj; otherwise, return false. * @throws
ClassCastException - if obj cannot be compared to the elements in * this
ArrayBinaryTree object. * @throws NullPointerException - if obj is null. */ @Override
public boolean contains(Object obj) { return getEntry(obj) != null; } /** * Ensures that
this ArrayBinaryTree object contains a specified element. The * worstTime(n) is O(n) for this
addition. * * @param element Element we want to be certain is contained within.
Hi,I have added the methods and main class as per your requirement.pdfannaelctronics
Hi,
I have added the methods and main class as per your requirement. it is working fine now.
Highlighted the code changes.
MyLinkedListTest.java
public class MyLinkedListTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
MyLinkedList list = new MyLinkedList();
list.addFirst(\"AAAAA\");
list.add(\"1\");
list.add(\"2\");
list.add(\"3\");
list.addLast(\"ZZZZZ\");
System.out.println(\"Linked List Elements : \"+list.toString());
System.out.println(\"First element: \"+list.getFirst());
System.out.println(\"Second element: \"+list.getLast());
System.out.println(\"Removed First Element: \"+list.removeFirst());
System.out.println(\"Now Linked List Elements : \"+list.toString());
System.out.println(\"Removed Last Element: \"+list.removeLast());
System.out.println(\"Now Linked List Elements : \"+list.toString());
System.out.println(\"Removed all element: \");
list.removeAll();
System.out.println(\"Now Linked List Elements : \"+list.toString());
}
}
MyLinkedList.java
public class MyLinkedList extends MyAbstractList {
private Node head, tail;
/** Create a default list */
public MyLinkedList() {
}
/** Create a list from an array of objects */
public MyLinkedList(E[] objects) {
super(objects);
}
/** Return the head element in the list */
public E getFirst() {
if (size == 0) {
return null;
}
else {
return (E)head.element;
}
}
/** Return the last element in the list */
public E getLast() {
if (size == 0) {
return null;
}
else {
return (E)tail.element;
}
}
/** Add an element to the beginning of the list */
public void addFirst(E e) {
Node newNode = new Node(e); // Create a new node
newNode.next = head; // link the new node with the head
head = newNode; // head points to the new node
size++; // Increase list size
if (tail == null) // the new node is the only node in list
tail = head;
}
/** Add an element to the end of the list */
public void addLast(E e) {
Node newNode = new Node(e); // Create a new for element e
if (tail == null) {
head = tail = newNode; // The new node is the only node in list
}
else {
tail.next = newNode; // Link the new with the last node
tail = tail.next; // tail now points to the last node
}
size++; // Increase size
}
/** Add a new element at the specified index in this list
* The index of the head element is 0 */
public void add(int index, E e) {
if (index == 0) {
addFirst(e);
}
else if (index >= size) {
addLast(e);
}
else {
Node current = head;
for (int i = 1; i < index; i++) {
current = current.next;
}
Node temp = current.next;
current.next = new Node(e);
(current.next).next = temp;
size++;
}
}
/** Remove the head node and
* return the object that is contained in the removed node. */
public E removeFirst() {
if (size == 0) {
return null;
}
else {
Node temp = head;
head = head.next;
size--;
if (head == null) {
tail = null;
}
return (E)temp.element;
}
}
/** Remove all elements from list */
public void removeAll() {
while(true) {
if (size == 0) {
break;
}
else {
Node temp = head;
head =.
Ethical Case Study 2Gloria is a housekeeper in an independent li.docxdebishakespeare
Ethical Case Study 2
Gloria is a housekeeper in an independent living community. While walking through a hallway, she noticed the door of a resident’s apartment was left open, which was unusual. She stepped in to check on Louis, and quickly realized that he was on the phone in his living room. As she turned to leave, she over heard him saying that he had stopped taking all of his medications because he was ready to die. She could tell that the person that he was speaking with was trying to reason with him. Gloria knows that Louis has a very loving and involved daughter that visits him every Saturday. She left the room determined that she would tell his daughter what she heard when she saw her on Saturday.
You have to answer all the questions below
What issues are facing Gloria? Discuss the possible ethical principles at play and your recommendation to Gloria.
Hint: Confidentiality, Beneficence, Self-determination
.
Ethical consideration is important in nursing practice, especial.docxdebishakespeare
Ethical consideration is important in nursing practice, especially when providing care to patients from diverse sociocultural backgrounds. The population of the United States comprises various ethnic/racial groups with different cultural and social beliefs, practice, norms, and values. There is an increasing disparities on the incidence and prevalence of type 2 diabetes among different communities in the United States. According to the Center for Disease Control and Prevention (CDC), Hispanics and African Americans have the highest incidence and prevalence of type 2 diabetes in the country (Concha, Mayer, Mezuk, & Avula, 2016). Caring for patients from different ethnic/racial groups require consideration of ethical principles and concepts to prevent ethical issues that may arise during nurse-patient interaction.
Recently, I cared for patient with type 2 diabetes mellitus who had been hospitalized for more than two weeks due to acute hypertension, partial loss of vision. Also, the patient had a chronic diabetic foot ulcer. The analysis of his medical history revealed that the diabetic foot ulcer had developed in the last two years and had never healed. The patient was so worried about his health status and kept asking when he was going to be discharged from the hospital. The patient came from the Hispanic community, which is one of minority groups with the highest incidence and prevalence of type 2 diabetes mellitus in the country. Being a culturally competent registered nurse, I had an obligation to take into account the specific ethnic background of the patient when providing care. Considering patient’s ethnic/racial background is important in providing quality, holistic, and patient-centered care based their health concerns, preferences, and values (Concha et al., 2016).
When collecting subjective data for analysis and planning for the care. I asked the patient about his perceptions about the possible causes of type 2 diabetes that he was suffering from. Hispanics have different beliefs in the causation of diabetes mellitus (Frieden, 2016). First, the patient believed that diabetes is a temporary condition that is not fatal. Second, the patient narrated a story that attempts to identify the cause of diabetes and concluded that they believe that people with “good diabetes” do not experience a lot of complications. The Hispanics use the term “good diabetes” when referring to the type of diabetes that do not require insulin for therapeutic purposes; non-insulin-dependent diabetes mellitus (T2DM) (Frieden, 2016). Also, the patient had a fatalistic attitude and believed that his health condition is likely to be a punishment from God.
The patient had a low health literacy level because caregivers had encouraged him to engage in some physical exercise and adopt a self-management approach as a way of controlling and preventing complications related to his condition, but he never implemented them. Also, the pat.
More Related Content
Similar to Required to augment the authors Binary Search Tree (BST) code to .docx
Write a C++ program that implements a binary search tree (BST) to man.pdfhardjasonoco14599
Write a C++ program that implements a binary search tree (BST) to manage a number of integer
items with different priorities. In order to do so. you will need to maintain a queue as an item in
the tree. Each queue item is an integer. All items in a given queue will have the same priority. As
a new item with a user-specified priority comes in, it should be enqueued in the queue with items
of that priority. A new queue may need to created in case a queue with that priority does not
exist. Use dynamic memory to manage nodes in the queue and BST. Implement the following:
Constructor. Destructor. Overloaded copy constructor. Overloaded assignment operator.
Overloaded \"==\" operator to check if two trees are equal. A tree t1 is equal to t2 if for every
queue in t1, a corresponding queue with the same priority exists in t2 with the same set of
elements (the order of the elements in the queue docs not matter). Overloaded \"
Solution
program using namespace std;
#define width_unit 5
class BStree
{
private:
class Node
{
public:
int data;
Node *left, *right;
Node(int d=0)
:data(d), left(NULL), right(NULL) {}
};
Node *root;
Node * trav(int, Node * &);
void chop(Node * N);
void copy(Node * N);
void print(ostream &, Node *, int) const;
void print(Node *, int) const;
public:
BStree(void);
~BStree(void);
bool find(int);
void insert(int);
void remove(int);
bool empty(void) const;
Tree(const BStree &);
const BStree & operator=(const BStree &);
friend ostream & operator<<(ostream &, const BStree &);
};
BStree::BStree(void)
{
root=NULL;
}
bool Tree::empty(void) const
{
return !root;
}
BStree::Node * BStree::trav(int foo, Node * & par)
{
Node * curr=root;
par=NULL;
while(curr && curr->data != foo)
{
par=curr;
if(foo < curr->data)
curr=curr->left;
else
curr=curr->right;
}
return curr;
}
bool BStree::find(int foo)
{
Node * par=NULL;
Node * curr=trav(foo, par);
return curr;
}
void BStree::insert(int foo)
{
Node * par=NULL;
Node * curr=trav(foo,par);
if(!curr)
{
curr= new Node(foo);
if(!par)
root=curr;
else if(foo < par->data)
par->left=curr;
else
par->right=curr;
}
}
void BStree::remove(const int foo)
{
Node * par=NULL;
Node * curr=trav(foo,par);
if(curr)
{
if(curr->left && curr->right)
{
Node * tmp=curr;
par=curr;
curr=curr->left;
while(curr->right)
{
par=curr;
curr=curr->right;
}
tmp->data=curr->data;
}
Node *tmp=(curr->left ? curr->left : curr->right);
if(!par)
root=tmp;
else if(par->data < curr->data)
par->right=tmp;
else
par->left=tmp;
delete curr;
}
}
void BStree::chop(Node *N)
{
if(N)
{
chop(N->left);
chop(N->right);
delete N;
}
}
BStree::~BStree(void)
{
chop(root);
}
BStree::BStree(const BStree & T)
{
root=NULL;
copy(T.root);
}
void BStree::copy(Node * N)
{
if(N)
{
insert(N->data);
copy(N->left);
copy(N->right);
}
}
const BStree & BStree::operator=(const BStree & T)
{
if(this != &T)
{
chop(root);
root=NULL;
copy(T.root);
}
return *this;
}
void BStree::print(ostream & ost, Node * curr, int level) const
{
if(curr)
{
print(ost,curr->right,level+1);
ost<data<le.
Write a program that accepts an arithmetic expression of unsigned in.pdfJUSTSTYLISH3B2MOHALI
Write a program that accepts an arithmetic expression of unsigned integers in postfix notation
and builds the arithmetic expression tree that represents that expression. From that tree, the
corresponding fully parenthesized infix expression should be displayed and a file should be
generated that contains the three address format instructions. This topic is discussed in the week
4 reading in module 2, section II-B. The main class should create the GUI shown below:
Pressing the Construct Tree button should cause the tree to be constructed and using that tree, the
corresponding infix expression should be displayed and the three address instruction file should
be generated. The postfix expression input should not be required to have spaces between every
token. Note in the above example that 9+- are not separated by spaces. The above example
should produce the following output file containing the three address instructions:
Add R0 5 9
Sub R1 3
R0 Mul R2 2 3
Div R3 R1 R2
Inheritance should be used to define the arithmetic expression tree. At a minimum, it should
involve three classes: an abstract class for the tree nodes and two derived classes, one for
operand nodes and another for operator nodes. Other classes should be included as needed to
accomplish good object-oriented design. All instance data must be declared as private.
You may assume that the expression is syntactically correct with regard to the order of operators
and operands, but you should check for invalid tokens, such as characters that are not valid
operators or operands such as 2a, which are not valid integers. If an invalid token is detected a
RuntimeException should be thrown and caught by the main class and an appropriate error
message should be displayed. Three Adddress Generator Enter Postfix Expression 359 2 3
Construct Tree Infix Expression ((3-(5 9))/ (2* 3
Solution
#include
#include
#include
#include
#include
struct TREE //Structure to represent a tree
{
char data;
struct TREE *right,*left,*root;
};
typedef TREE tree; /* Stack Using Linked List */
struct Stack //Structure to represent Stack
{
struct TREE *data;
struct Stack *next,*head,*top; //Pointers to next node,head and top
};
typedef struct Stack node;
node *Nw; //Global Variable to represent node
void initialize(node *&n)
{
n = new node;
n -> next = n -> head = n -> top = NULL;
}
void create(node *n)
{
Nw = new node; //Create a new node
Nw -> next = NULL; //Initialize next pointer field
if(n -> head == NULL) //if first node
{
n -> head = Nw; //Initialize head
n -> top = Nw; //Update top
}
}
void push(node *n,tree *ITEM)
{
node *temp = n -> head;
if(n -> head == NULL) //if First Item is Pushed to Stack
{
create(n); //Create a Node
n -> head -> data = ITEM; //Insert Item to head of List
n -> head = Nw;
return; //Exit from Function
}
create(n); //Create a new Node
Nw -> data = ITEM; //Insert Item
while(temp -> next != NULL)
temp = temp -> next; //Go to Last Node
temp -> next = Nw; //Point New node
n -> top = Nw; //Upda.
Running Head: Discussion Board 1
Discussion Board 3
Discussion Board
Student’s Name
Institution Affiliation
My topics for this discussion will lean on the immigration and the plight of immigrants. This is a subject that will bring a good platform to form an informative as well as persuasive speech. I will specifically address the value of policy making in the management of immigration trends that are increasing in the USA as well as western countries (Zatz, & Rodriguez, 2015). The topic will be “Do illegal immigrants deserve a hearing in the countries they seek asylum or they should just be deported impartially?” I think this is a contentious issue in the world today.
There are many policies that have been established by various international organizations such as UN in regard to Immigration. The underlying issues in this matter still remain dormant and unresolved. The fundamental question of concern is addressing the parties that should be concerned with this matter. I will be addressing the international community as my audience, particularly the UN, countries. The speech will also include recommendations that will be suggested for handling of the matter. It will also give a discourse of the current situation in different parts of the world such as USA and Europe. This will paint a picture of the dire need of the situation and the dangers that immigrants are facing every day. It will also address the plight of illegal immigrants who I will argue that they deserve humanly just and fair treatment whenever they are met by the hand of the law. The speech is intended to bring an evaluation of the essence of humanity in considering one another and building bridges that alleviate instead of perpetuating human suffering in the world.
References
Zatz, M. S., & Rodriguez, N. (2015). Dreams and nightmares: Immigration policy, youth, and families. University of California Press.
ASS12/assg-12.cppASS12/assg-12.cpp/**
*
* @description Assignment 12 Binary Search Trees
*/
#include<cassert>
#include<iostream>
#include"BinaryTree.hpp"
usingnamespace std;
/** main
* The main entry point for this program. Execution of this program
* will begin with this main function.
*
* @param argc The command line argument count which is the number of
* command line arguments provided by user when they started
* the program.
* @param argv The command line arguments, an array of character
* arrays.
*
* @returns An int value indicating program exit status. Usually 0
* is returned to indicate normal exit and a non-zero value
* is returned to indicate an error condition.
*/
int main(int argc,char** argv)
{
// -----------------------------------------------------------------------
...
Array is a container which can hold a fix number of items and these items should be of the same type. Most of the data structures make use of arrays to implement their algorithms. Following are the important terms to understand the concept of array.
Please help solve this in C++ So the program is working fin.pdfankit11134
Please help solve this in C++. So the program is working fine but when submitting it, it gives me a
code -11, and I believe the problem is that after inserting the numbers it removes them one by one
until the last in the list, and when it tries to remove the last number in the list that is when it
counters the problem. Below is the full code but you just need to change something in the
SortedNumberList.h file under the bool remove function.
4.18 LAB: Sorted number list implementation with linked lists Step 1: Inspect the Node.h file
Inspect the class declaration for a doubly-linked list node in Node.h. Access Node.h by clicking on
the orange arrow next to main.cpp at the top of the coding window. The Node class has three
member variables: - a double data value, - a pointer to the next node, and - a pointer to the
previous node. Each member variable is protected. So code outside of the class must use the
provided getter and setter member functions to get or set a member variable. Node.h is read only,
since no changes are required. Step 2: Implement the Insert() member function A class for a
sorted, doubly-linked list is declared in SortedNumberList.h. Implement the SortedNumberList
class's Insert() member function. The function must create a new node with the parameter value,
then insert the node into the proper sorted position in the linked list. Ex: Suppose a
SortedNumberList's current list is 2347.2586, then Insert(33.5) is called. A new node with data
value 33.5 is created and inserted between 23 and 47.25, thus preserving the list's sorted order
and yielding: 2335.547.2586Step 3: Test in develop mode Code in main() takes a space-
separated list of numbers and inserts each into a SortedNumberList. The list is displayed after
each insertion. Ex: If input is 77154263.5 then output is: List after inserting 77 : 77 List after
inserting 15 : 1577 List after inserting -42 : -421577 List after inserting 63.5: -421563.577 Try
various program inputs, ensuring that each outputs a sorted list. Step 4: Implement the Remove()
member function Implement the SortedNumberList class's Remove(0 member function. The
function takes a parameter for the number to be removed from the list. If the number does not
exist in the list, the list is not changed and false is returned. Otherwise, the first instance of the
number is removed from the list and true is returned. Uncomment the commented-out part in
main() that reads a second input line and removes numbers from the list. Test in develop mode to
ensure that insertion and removal both work properly, then submit code for grading. Ex: If input is
841972841961 then output is: List after inserting 84: 84 List after inserting 72 : 7284 List after
inserting 19: 1972 84 List after inserting 61: 1961 : 72 8 List after removing 19: 6172 84 List after
removing 84: 6172Current file: main.cpp - // Insert each value and show the sorted List's contents
after each insertion sortedNumberList list; for (auto term : terms) { doubl.
Given the following ADT definition of a stack to use stack .docxshericehewat
Given the following ADT definition of a stack to use:
/** stack (base class)
* The basic definition of the Stack Abstract Data Type (ADT)
* and stack operations. All declared functions here are
* virtual, they must be implemented by concrete derived
* classes.
*/
template <class T>
class Stack
{
public:
/** clear
* Method to clear out or empty any items on stack,
* put stack back to empty state.
* Postcondition: Stack is empty.
*/
virtual void clear() = 0;
/** isEmpty
* Function to determine whether the stack is empty. Needed
* because it is undefined to pop from empty stack. This
* function will not change the state of the stack (const).
*
* @returns bool true if stack is empty, false otherwise.
*/
virtual bool isEmpty() const = 0;
/** push
* Add a new item onto top of stack.
*
* @param newItem The item of template type T to push on top of
* the current stack.
*/
virtual void push(const T& newItem) = 0;
/** top
* Return the top item from the stack. Note in this ADT, peeking
* at the top item does not remove the top item. Some ADT combine
* top() and pop() as one operation. It is undefined to try and
* peek at the top item of an empty stack. Derived classes should
* throw an exception if this is attempted.
*
* @returns T Returns the top item from stack.
*/
virtual T top() const = 0;
/** pop
* Remove the item from the top of the stack. It is undefined what
* it means to try and pop from an empty stack. Derived classes should
* throw an exception if pop() from empty is attempted.
*/
virtual void pop() = 0;
/** size
* Accessor method to provide the current size of the stack.
*
* @returns int The current size (number of items) on the stack.
*/
virtual int size() const = 0;
};
perform the following tasks by writing code that uses a stack to accomplish the task. You will
need to create a stack of the needed type, then use the methods of the stack abstraction (push,
top, pop, etc.) to solve the given task asked for.
Question 7 (5 points)
Given a stack of integers, calculate the sum of the integer values. Also, the stack should still be
unchanged after you have calculated the sum Hint: take the items off the stack to sum them up
and keep them on a second temporary stack so you can put them all back on after you have
calculated the sum.
ANSWER FOR NUMBER 7:
int sumStackOfIntegers(Stack<int> currentStack) {
Stack<int> tempStack;
int sum = 0;
while(!currentStack.isEmpty()) {
int temp = currentStack.top();
tempStack.push(temp);
currentStack.pop();
sum += temp;
}
while(!tempStack.isEmpty()) {
int temp = tempStack.top();
currentStack.push(temp);
tempStack.pop();
}
return sum;
}
Stack Implementation
Given the following linked list implementation of a Stack ADT (this is the same implementation
you used in Assignment 10), add the asked for additional member methods to the linked list stack
implementation.
/** Node
* A basic node contaning an item and a link to t ...
Use the following data set that compares age to average years lef.docxdickonsondorris
Use the following data set that compares age to average "years left to live" to answer the following questions.
Age 10 20 30 40 50 60 70 80 90 100
Years to live 59.2 49.6 40.7 31.9 24.0 17.2 11.6 7.2 4 .4 2.8
a) Show the scatterplot for this data with the least squares regression line. Find R^2. How much of the variation is explained by the regression line?
b) Experiment with the non-linear regressions available on the calculator. Which seem to fit? Show the scatterplot with three different regression curves from the calculator. Label each equation, as well as the applicable R^2.
c) Choose a regression equation to predict how many "years left" a person has if he is now 101 years old. Can he count on celebrating Christmas 2015?
InfoTest.javaInfoTest.javapackage assignment1;
importstatic org.junit.Assert.*;
import org.junit.Test;
publicclassInfoTest{
@Test
publicvoid testInfo(){
Info tempInfo =newInfo();
assertNotNull(tempInfo.tmp);
}
@Test
publicvoid testInsert(){
Info tempInfo =newInfo();
// Insert into an empty list
tempInfo.insert(30);
assertEquals(30, tempInfo.get(0));
// Insert an item to be placed at the beginning of the list
tempInfo.insert(4);
assertEquals(4, tempInfo.get(0));
assertEquals(30, tempInfo.get(1));
// Insert an item to be placed at the end of the list
tempInfo.insert(20);
assertEquals(20, tempInfo.get(1));
assertEquals(30, tempInfo.get(2));
// Insert an which already exists
tempInfo.insert(20);
assertEquals(4, tempInfo.get(0));
assertEquals(20, tempInfo.get(1));
assertEquals(30, tempInfo.get(2));
}
@Test
publicvoid testDelete(){
Info tempInfo =newInfo();
tempInfo.insert(15);
tempInfo.insert(5);
tempInfo.insert(10);
// delete from the middle
tempInfo.delete(10);
assertEquals(5, tempInfo.get(0));
assertEquals(15, tempInfo.get(1));
// delete from the beginning
tempInfo.insert(10);
tempInfo.delete(5);
assertEquals(10, tempInfo.get(0));
assertEquals(15, tempInfo.get(1));
// delete from the end
tempInfo.insert(5);
tempInfo.delete(15);
assertEquals(5, tempInfo.get(0));
assertEquals(10, tempInfo.get(1));
// delete something that does not exist
tempInfo.insert(15);
tempInfo.delete(7);
assertEquals(5, tempInfo.get(0));
assertEquals(10, tempInfo.get(1));
assertEquals(15, tempInfo.get(1));
}
@Test
publicvoid testGet(){
Info tempInfo =newInfo();
tempInfo.insert(15);
tempInfo.insert(5);
tempInfo.insert(10);
// get items at the beginning, middle, and end of the list
assertEquals(5, tempInfo.get(0));
assertEquals(10, tempInfo.get(1));
assertEquals(15, tempInfo.get(2));
// get an unexisting item
assertNull(tempInfo.get(3));
}
@Test
publicvoid testCount(){
Info tempInfo =newInfo();
/ ...
Assg 12 Binary Search TreesCOSC 2336 Spring 2019April.docxfestockton
Assg 12: Binary Search Trees
COSC 2336 Spring 2019
April 10, 2019
Dates:
Due: Sunday April 21, by Midnight
Objectives
� Practice recursive algorithms
� Learn how to construct a binary tree using pointers/linked nodes
� Learn about binary tree traversal
Description
In this assignment you will be given the beginning of a BinaryTree imple-
mentation using linked nodes via pointers. You will be implementing some
of the basic function of a BinaryTree abstract data type. The abstraction
we are using for the BinaryTreeNode and the BinaryTree are similar to
the Sha�er BSTNode (pg. 156,161) and the BST abstract class and linked
pointer implementation (Sha�er pg. 171), but we will de�ne our own version
and simplify some of the functions and interface.
You have been given a BinaryTree.[cpp|hpp] �le that de�nes the BinaryTreeNode
structure and BinaryTree class. This class is current not templatized, the
constructed trees only hold items of simple type int (one of the extra credit
opportunities suggests you templatize your resulting class). The BinaryTree
has a constructor, and you have been provided a tostring() method and
an overloaded operator�() so that you can display the current contents of
the tree.
For this assignment you need to perform the following tasks.
1
1. In order to test your class, we �rst have to get a working capability to
insert new items into the BinaryTree, which isn't the simplest task to
start with, but we can't really test others until we can add new items.
For many of the functions in this assignment, you will be required to
implement them using a recursive function. Thus many of the func-
tions for your BinaryTree will have a public function that asks as the
interface that is called by users of the BinaryTree, and a private ver-
sion that actually does the work using a recursive algorithm. I will
give you the signature you need for the insert() functions:
class BinaryTree
{
private:
BinaryTreeNode* insert(BinaryTreeNode* node, const int item);
public:
void insert(const int item);
}
Lets start �rt with the public insert() function. This function is the
public interface to insert a new item into the tree. Since we are only
implementing a tree of int items, you simply pass in the int value that
is to be inserted. This function basically only needs to call the private
insert() function, passing in the current root of the tree as the �rst
parameter, and the item to be inserted as the second parameter. Notice
that the private insert() returns a pointer to a BinaryTreeNode.
The private insert() function is a recursive function. The base case
is simple. If the node you pass in is NULL, then that means you have
found the location where a new node should be created and inserted.
So for the base case, when node is NULL you should dynamically create
a new BinaryTreeNode item, assign the item and make sure that the
left and right pointers are initialized to NULL. When you create a new
node like this, you should retu ...
MAINCPP include ltiostreamgt include ltstringgt u.pdfadityastores21
MAIN.CPP
#include <iostream>
#include <string>
using namespace std;
#include "bstree.h"
// Prints a single string, used by FSTree::inorder to print all
// values in the tree in correct order.
void print_string (string s) { cout << s << endl; }
// Prints a single string preceeded by a number of hyphens, used by
// BSTree::preorder to print a visual representation of the tree.
void print_string_depth (string s, int n) {
for (int i = 0; i < n; i++)
cout << '-';
cout << s << endl;
}
int main () {
// Create a binary search tree.
BSTree<string> t;
// Insert some strings for testing.
t.insert("dog");
t.insert("bird");
t.insert("cat");
t.insert("turtle");
t.insert("giraffe");
t.insert("snake");
t.insert("deer");
t.insert("groundhog");
t.insert("horse");
// Output the values stored in the tree.
cout << "Values stored in the tree are:n";
t.inorder(print_string);
cout << "n";
cout << "The structure of the tree is as follows:n";
t.preorder(print_string_depth);
cout << "n";
}
BSTREE.h
#pragma once
// A Binary Search Tree implementation.
template <typename T>
class BSTree {
private:
// A node in the tree. Each node has pointers to its left and right nodes
// as well as its parent. When a node is created, the parent and data item
// must be provided.
class node {
public:
T data;
node* left;
node* right;
node* parent;
node (const T& d, node* p) {
parent = p;
data = d;
left = right = nullptr;
}
};
// Pointer to the root node. Initially this is null for an empty tree.
node* root;
// Copy the subtree of another BSTree object into this object. Used by
// the copy constructor and assignment operator.
void copy (node* p) {
if (p) { // If p points to a node...
insert(p->data); // Insert data item
copy(p->left); // Copy the left subtree
copy(p->right); // Copy the right subtree
}
}
// Destroy a node and all nodes in both subtrees. Called by the
// destructor.
void destroy (node* p) {
if (p) { // If p is not null...
destroy(p->left); // Destroy the left subtree
destroy(p->right); // Destroy the right subtree
delete p; // Destroy the node
}
}
// Helper function to determine if a data value is contained in the tree.
// Takes the data value being searched and a pointer to the node in the
// tree. Returns pointer to node in which data item is found, a null
// pointer otherwise.
node* find (const T& d, node* p) const {
// Given: p is a pointer to an existing node
if (d == p->data) // Is this the value we're looking for?
return p;
if (d < p->data) // Check left side, if null then not found
return p->left ? find(d, p->left) : nullptr;
return p->right ? find(d, p->right) : nullptr; // Check right side...
}
// Helper function to insert a data item into the tree. Takes the data
// and a pointer to a node in the tree. Recursively decends down the tree
// until position were insertion should take place is found.
void insert (const T& d, node* p) {
// Given: p is a pointer to an existing node (root of a subtree)
if (d < p->data) { // Insert into left subtree?
if (p->left) // Left.
Describe a data structure to represent sets of elements (each element.pdfrajeshjain2109
Describe a data structure to represent sets of elements (each element with a unique key) that
would support the following operations: insert(x, A) - insert an element x into A (assume the key
of x is not in .4 yet) count (A, k) - return the number of elements in A with key at least k.
Solution
we can use Hashset for this.a simple code in hashset is given below
public class MyNode
{
...
}
public class MyDataStructure
{
private HashSet nodes = new HashSet();
///
/// Inserts an element to this data structure.
/// If the element already exists, returns false.
/// Complexity is averaged O(1).
///
public bool Add(MyNode node)
{
return node != null && this.nodes.Add(node);
}
///
/// Removes a random element from the data structure.
/// Returns the element if an element was found.
/// Returns null if the data structure is empty.
/// Complexity is averaged O(1).
///
public MyNode Pop()
{
// This loop can execute 1 or 0 times.
foreach (MyNode node in nodes)
{
this.nodes.Remove(node);
return node;
}
return null;
}
}
the unique key can also be achieved using dictioneries
hence code for this is given below:
public class FixedIntDictionary
{
// Our internal node structure.
// We use structs instead of objects to not add pressure to the garbage collector.
// We mantains our own way to manage garbage through the use of a free list.
private struct Entry
{
// The key of the node
internal int Key;
// Next index in pEntries array.
// This field is both used in the free list, if node was removed
// or in the table, if node was inserted.
// -1 means null.
internal int Next;
// The value of the node.
internal T Value;
}
// The actual hash table. Contains indices to pEntries array.
// The hash table can be seen as an array of singlt linked list.
// We store indices to pEntries array instead of objects for performance
// and to avoid pressure to the garbage collector.
// An index -1 means null.
private int[] pBuckets;
// This array contains the memory for the nodes of the dictionary.
private Entry[] pEntries;
// This is the first node of a singly linked list of free nodes.
// This data structure is called the FreeList and we use it to
// reuse removed nodes instead of allocating new ones.
private int pFirstFreeEntry;
// Contains simply the number of items in this dictionary.
private int pCount;
// Contains the number of used entries (both in the dictionary or in the free list) in pEntries
array.
// This field is going only to grow with insertions.
private int pEntriesCount;
///
/// Creates a new FixedIntDictionary.
/// tableBucketsCount should be a prime number
/// greater than the number of items that this
/// dictionary should store.
/// The performance of this hash table will be very bad
/// if you don\'t follow this rule!
///
public FixedIntDictionary(int tableBucketsCount)
{
// Our free list is initially empty.
this.pFirstFreeEntry = -1;
// Initializes the entries array with a minimal amount of items.
this.pEntries = new Entry[8];
// Allocate buckets and initial.
Assg 12 Binary Search Trees COSC 2336assg-12.cppAssg 12 Binary .docxfestockton
Assg 12 Binary Search Trees COSC 2336/assg-12.cppAssg 12 Binary Search Trees COSC 2336/assg-12.cpp/**
* @author Jane Programmer
* @cwid 123 45 678
* @class COSC 2336, Spring 2019
* @ide Visual Studio Community 2017
* @date April 8, 2019
* @assg Assignment 12
*
* @description Assignment 12 Binary Search Trees
*/
#include<cassert>
#include<iostream>
#include"BinaryTree.hpp"
usingnamespace std;
/** main
* The main entry point for this program. Execution of this program
* will begin with this main function.
*
* @param argc The command line argument count which is the number of
* command line arguments provided by user when they started
* the program.
* @param argv The command line arguments, an array of character
* arrays.
*
* @returns An int value indicating program exit status. Usually 0
* is returned to indicate normal exit and a non-zero value
* is returned to indicate an error condition.
*/
int main(int argc,char** argv)
{
// -----------------------------------------------------------------------
cout <<"--------------- testing BinaryTree construction ----------------"<< endl;
BinaryTree t;
cout <<"<constructor> Size of new empty tree: "<< t.size()<< endl;
cout << t << endl;
assert(t.size()==0);
cout << endl;
// -----------------------------------------------------------------------
cout <<"--------------- testing BinaryTree insertion -------------------"<< endl;
//t.insert(10);
//cout << "<insert> Inserted into empty tree, size: " << t.size() << endl;
//cout << t << endl;
//assert(t.size() == 1);
//t.insert(3);
//t.insert(7);
//t.insert(12);
//t.insert(15);
//t.insert(2);
//cout << "<insert> inserted 5 more items, size: " << t.size() << endl;
//cout << t << endl;
//assert(t.size() == 6);
cout << endl;
// -----------------------------------------------------------------------
cout <<"--------------- testing BinaryTree height -------------------"<< endl;
//cout << "<height> Current tree height: " << t.height() << endl;
//assert(t.height() == 3);
// increase height by 2
//t.insert(4);
//t.insert(5);
//cout << "<height> after inserting nodes, height: " << t.height()
// << " size: " << t.size() << endl;
//cout << t << endl;
//assert(t.height() == 5);
//assert(t.size() == 8);
cout << endl;
// -----------------------------------------------------------------------
cout <<"--------------- testing BinaryTree clear -------------------"<< endl;
//t.clear();
//cout << "<clear> after clearing tree, height: " << t.height()
// << " size: " << t.size() << endl;
//cout << t << endl;
//assert(t.size() == 0);
//assert(t.height() == 0);
cout << endl;
// return 0 to indicate successful completion
return0;
}
Assg 12 Binary Search Trees COSC 2336/assg-12.pdf
Assg 12: Binary Search Trees
COSC 2336 Spring 2019
April 10, 2019
Dates:
Due: Sunday April 21, by Midnight
Objectives
� Practice recursive algorithms
� Learn how to construct a binary tree usi ...
AvlTree.h
#ifndef AVL_TREE_H
#define AVL_TREE_H
#include "dsexceptions.h"
#include <iostream> // For NULL
#include <queue> // For level order printout
#include <vector>
#include <algorithm> // For max() function
using namespace std;
// AvlTree class
//
// CONSTRUCTION: with ITEM_NOT_FOUND object used to signal failed finds
//
// ******************PUBLIC OPERATIONS*********************
// Programming Assignment Part I
// bool empty( ) --> Test for empty tree @ root
// int size( ) --> Quantity of elements in tree
// int height( ) --> Height of the tree (null == -1)
// void insert( x ) --> Insert x
// void insert( vector<T> ) --> Insert whole vector of values
// void remove( x ) --> Remove x (unimplemented)
// bool contains( x ) --> Return true if x is present
// Comparable findMin( ) --> Return smallest item
// Comparable findMax( ) --> Return largest item
// boolean isEmpty( ) --> Return true if empty; else false
// void printTree( ) --> Print tree in sorted (in) order
// void printPreOrder( ) --> Print tree in pre order
// void printPostOrder( ) --> Print tree in post order
// void printInOrder( ) --> Print tree in *in* order
// Programming Assignment Part II (microassignment)
// void makeEmpty( ) --> Remove and delete all items
// void ~AvlTree( ) --> Big Five Destructor
// AvlTree(const AvlTree &other) --> BigFive Copy Constructor
// AvlTree(const AvlTree &&other) --> BigFive Move Constructor
// AvlTree &operator= ( AvlTree & other ) --> Big Five Copy *assignment* operator
// AvlTree &operator= ( AvlTree && other ) --> Big Five Move *assignment* operator
// void printLevelOrder( ) --> Print tree in LEVEL order :-)
// ******************ERRORS********************************
// Throws UnderflowException as warranted
template <typename Comparable>
class AvlTree
{
public:
/**
* Basic constructor for an empty tree
*/
AvlTree( ) : root( NULL )
{
//cout << " [d] AvlTree constructor called. " << endl;
}
/**
* Vector of data initializer (needed for move= operator rvalue)
*/
AvlTree( vector<Comparable> vals ) : root( NULL )
{
insert(vals);
}
//*******************************************************************************************
// START AVL TREES PART II - TODO: Implement
// Other functions to look for include: clone, makeEmpty, printLevelOrder
/**
* Destroy contents of the AvlTree object - Big Five Destructor
*/
~AvlTree( )
{
//cout << " [d] AvlTree Destructor called. " << endl;
// Empty out the AVL Tree and destroy all nodes (makeEmpty?)
}
/**
* Copy other to new object - Big Five Copy Constructor
*/
AvlTree( const AvlTree &other ) : root( NULL )
{
cout << " [d] Copy Constructor Called." << endl;
// Copy contents of other to ourselves (maybe clone?)
// Get a deep copy of other's tree
}
/* ...
(Parent reference for BST) Redefine TreeNode by adding a reference to.pdfarihantelehyb
(Parent reference for BST) Redefine TreeNode by adding a reference to a node\'s parent, as
shown below\': Reimplement the insert and delete methods in the BST class to update the parent
for each node in the tree. Add the following new method in BST:/** Returns the node for the
specified element. * Returns null if the element is not in the tree. */private TreeNode getNode(E
element)/** Returns true if the node for the element is a leaf */private boolean isLeaf(E
element)/** Returns the path of elements from the specified element * to the root in an array
list. */public ArrayList getPath(E e) Write a test program that prompts the user to enter 10
integers, adds them to the tree, deletes the first integer from the tree, and displays the paths for
all leaf nodes. Here is a sample run:
Solution
#include
#include
void swap(char *x, char *y)
{
char temp;
temp = *x;
*x = *y;
*y = temp;
void permute(char *a, int l, int r)
{
int i;
if (l == r)
printf(\"%s\ \", a);
else
{
for (i = l; i <= r; i++)
{
swap((a+l), (a+i));
permute(a, l+1, r);
swap((a+l), (a+i)); //backtrack
}
}
}
int main()
{
char str[] = \"ABC\";
int n = strlen(str);
permute(str, 0, n-1);
return 0;
}
part ii radix sort:
c++
#include
using namespace std;
int getMax(int arr[], int n)
{
int mx = arr[0];
for (int i = 1; i < n; i++)
if (arr[i] > mx)
mx = arr[i];
return main()
void countSort(int arr[], int n, int exp
for (i = 0; i < n; i++)
count[ (arr[i]/exp)%10 ]++;
for (i = 1; i < 10; i++)
count[i] += count[i - 1];
for (i = n - 1; i >= 0; i--)
{
output[count[ (arr[i]/exp)%10 ] - 1] = arr[i];
count[ (arr[i]/exp)%10 ]--;
}
for (i = 0; i < n; i++)
arr[i] = output[i];
}
adixsort(int arr[], int n)
{
int m = getMax(arr, n);
for (int exp = 1; m/exp > 0; exp *= 10)
countSort(arr, n, exp);
}
void print(int arr[], int n)
{
for (int i = 0; i < n; i++)
cout << arr[i] << \" \";
}
int main()
{
int arr[] = {170, 45, 75, 90, 802, 24, 2, 66};
int n = sizeof(arr)/sizeof(arr[0]);
radixsort(arr, n);
print(arr, n);
return 0;
}
java:
import java.io.*;
import java.util.*;
class Radix {
static int getMax(int arr[], int n)
{
int mx = arr[0];
for (int i = 1; i < n; i++)
if (arr[i] > mx)
mx = arr[i];
return mx;
}
static void countSort(int arr[], int n, int exp)
{
int output[] = new int[n]; // output array
int i;
int count[] = new int[10];
Arrays.fill(count,0);
for (i = 0; i < n; i++)
count[ (arr[i]/exp)%10 ]++;
for (i = 1; i < 10; i++)
count[i] += count[i - 1];
for (i = n - 1; i >= 0; i--)
{
output[count[ (arr[i]/exp)%10 ] - 1] = arr[i];
count[ (arr[i]/exp)%10 ]--;
}
for (i = 0; i < n; i++)
arr[i] = output[i];
}
static void radixsort(int arr[], int n)
{
int m = getMax(arr, n);
for (int exp = 1; m/exp > 0; exp *= 10)
countSort(arr, n, exp);
}
static void print(int arr[], int n)
{
for (int i=0; i
#include
void swap(char *x, char *y)
{
char temp;
temp = *x;
*x = *y;
*y = temp;
void permute(char *a, int l, int r)
{
int i;
if (l == r)
printf(\"%s\ \", a);
else
{
for (i = l; i <= r; i++)
{
swap((a+l), (a+i));
permute(a, l+1, .
ReversePoem.java ---------------------------------- public cl.pdfravikapoorindia
ReversePoem.java :-
---------------------------------
public class ReversePoem {
/*This programs has you display a pessimistic poem from a list of phrases*/
// and then reverse the phrases to find another more optimistic poem.
public static void main(String[] args) throws Exception
{
//Queue object
MyQueue queue = new MyQueue<>();
//Stack object
MyStack stack = new MyStack<>();
//String buffer to apppend all Strings
StringBuffer sb = new StringBuffer();
// Create a single String object from the 16 Strings below
String set1 = \"I am part of a lost generation#and I refuse to believe that#\";
sb.append(set1);
String set2 = \"I can change the world#I realize this may be a shock but#\";
sb.append(set2);
String set3 = \"\'Happiness comes from within\'#is a lie, and#\";
sb.append(set3);
String set4 = \"\'Money will make me happy\'#So in 30 years I will tell my children#\";
sb.append(set4);
String set5 = \"they are not the most important thing in my life#\";
sb.append(set5);
String set6 = \"My employer will know that#I have my priorities straight because#\";
sb.append(set6);
String set7 = \"work#is more important than#family#I tell you this#\";
sb.append(set7);
String set8 = \"Once upon a time#Families stayed together#\";
sb.append(set8);
String set9 = \"but this will not be true in my era#\";
sb.append(set9);
String set10 = \"This is a quick fix society#Experts tell me#\";
sb.append(set10);
String set11 = \"30 years from now, I will be celebrating the 10th anniversary of my
divorce#\";
sb.append(set11);
String set12 = \"I do not concede that#I will live in a country of my own making#\";
sb.append(set12);
String set13 = \"In the future#Environmental destruction will be the norm#\";
sb.append(set13);
String set14 = \"No longer can it be said that#My peers and I care about this earth#\";
sb.append(set14);
String set15 = \"It will be evident that#My generation is apathetic and lethargic#\";
sb.append(set15);
String set16 = \"It is foolish to presume that#There is hope#\";
sb.append(set16);
String finalString = sb.toString();
String itmes[] = finalString.split(\"#\");
System.out.println(\"========== Original Phrase ==============\");
for(int i = 0 ; i < itmes.length;i++){
queue.enqueue(itmes[i]);
System.out.println(itmes[i]);
}
for(int i = 0 ; i < itmes.length;i++){
stack.push(queue.dequeue());
}
System.out.println(\"========== Reverse Phrase ==============\");
for(int i = 0 ; i < itmes.length;i++){
System.out.println(stack.pop());
}
/* You are given a list of phrases in Strings; the phrases
are separated by pound signs: \'#\':
1. Create a single String object from this list.
2. Then, split the String of phrases into an array of
phrases using the String split method.
3. Display a poem by walking through the array and
displaying each phrase one per line.
4. And, at the same time, place each phrase on a
MyQueue object using only the enqueue method.
5. After all the phrases have been placed on the queue,
transfer the phrases from the MyQueue object to a
MyS.
On the code which has a class in which I implementing a binary tree .pdfwasemanivytreenrco51
On the code which has a class in which I implementing a binary tree using an array. This array,
named store, stores Node in entries corresponding to
nodes in the tree and null if the node does not exist. Complete the countLeavesmethod so that it
returns the number of leaves in this tree.
Code:
Solution
import java.util.AbstractSet; import java.util.Arrays; import java.util.Iterator; import
java.util.NoSuchElementException; /** * Implementation of an abstract set using an array-
based binary tree. This is * used to help teach binary tree\'s and will have more details explained
in * future lectures. * * @author William J. Collins * @author Matthew Hertz * @param
Data type (which must be Comparable) of the elements in this tree. */ public class
ArrayBinaryTree> extends AbstractSet { /** Entry in the data store where the root node can be
found. */ private static final int ROOT = 0; /** Array used to store the nodes which consist of
this binary tree. */ protected Node[] store; /** Number of elements within the tree. */
protected int size; /** * Initializes this ArrayBinaryTree object to be empty. This creates the
array * in which items will be stored. */ @SuppressWarnings(\"unchecked\") public
ArrayBinaryTree() { store = new Node[63]; size = 0; } /** * Initializes this
ArrayBinaryTree object to contain a shallow copy of a * specified ArrayBinaryTree object.
The worstTime(n) is O(n), where n is the * number of elements in the specified
ArrayBinaryTree object. * * @param otherTree The tree which will be copied to create our
new tree, */ @SuppressWarnings(\"unchecked\") public ArrayBinaryTree(ArrayBinaryTree
otherTree) { store = (Node[]) Arrays.copyOf(otherTree.store, otherTree.store.length); size =
otherTree.size; } public int countLeaves() { } /** * Returns the size of this
ArrayBinaryTree object. * * @return the size of this ArrayBinaryTree object. */
@Override public int size() { return size; } /** * Returns an iterator that will return the
elements in this ArrayBinaryTree, * but without any specific ordering. * * @return Iterator
positioned at the smallest element in this ArrayBinaryTree * object. */ @Override
public Iterator iterator() { return new ArrayTreeIterator(); } /** * Determines if there is at
least one element in this ArrayBinaryTree object * that equals a specified element. The
worstTime(n) is O(n) and * averageTime(n) is O(log n). * * @param obj - the element
sought in this ArrayBinaryTree object. * @return true - if there is an element in this
ArrayBinaryTree object that * equals obj; otherwise, return false. * @throws
ClassCastException - if obj cannot be compared to the elements in * this
ArrayBinaryTree object. * @throws NullPointerException - if obj is null. */ @Override
public boolean contains(Object obj) { return getEntry(obj) != null; } /** * Ensures that
this ArrayBinaryTree object contains a specified element. The * worstTime(n) is O(n) for this
addition. * * @param element Element we want to be certain is contained within.
Hi,I have added the methods and main class as per your requirement.pdfannaelctronics
Hi,
I have added the methods and main class as per your requirement. it is working fine now.
Highlighted the code changes.
MyLinkedListTest.java
public class MyLinkedListTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
MyLinkedList list = new MyLinkedList();
list.addFirst(\"AAAAA\");
list.add(\"1\");
list.add(\"2\");
list.add(\"3\");
list.addLast(\"ZZZZZ\");
System.out.println(\"Linked List Elements : \"+list.toString());
System.out.println(\"First element: \"+list.getFirst());
System.out.println(\"Second element: \"+list.getLast());
System.out.println(\"Removed First Element: \"+list.removeFirst());
System.out.println(\"Now Linked List Elements : \"+list.toString());
System.out.println(\"Removed Last Element: \"+list.removeLast());
System.out.println(\"Now Linked List Elements : \"+list.toString());
System.out.println(\"Removed all element: \");
list.removeAll();
System.out.println(\"Now Linked List Elements : \"+list.toString());
}
}
MyLinkedList.java
public class MyLinkedList extends MyAbstractList {
private Node head, tail;
/** Create a default list */
public MyLinkedList() {
}
/** Create a list from an array of objects */
public MyLinkedList(E[] objects) {
super(objects);
}
/** Return the head element in the list */
public E getFirst() {
if (size == 0) {
return null;
}
else {
return (E)head.element;
}
}
/** Return the last element in the list */
public E getLast() {
if (size == 0) {
return null;
}
else {
return (E)tail.element;
}
}
/** Add an element to the beginning of the list */
public void addFirst(E e) {
Node newNode = new Node(e); // Create a new node
newNode.next = head; // link the new node with the head
head = newNode; // head points to the new node
size++; // Increase list size
if (tail == null) // the new node is the only node in list
tail = head;
}
/** Add an element to the end of the list */
public void addLast(E e) {
Node newNode = new Node(e); // Create a new for element e
if (tail == null) {
head = tail = newNode; // The new node is the only node in list
}
else {
tail.next = newNode; // Link the new with the last node
tail = tail.next; // tail now points to the last node
}
size++; // Increase size
}
/** Add a new element at the specified index in this list
* The index of the head element is 0 */
public void add(int index, E e) {
if (index == 0) {
addFirst(e);
}
else if (index >= size) {
addLast(e);
}
else {
Node current = head;
for (int i = 1; i < index; i++) {
current = current.next;
}
Node temp = current.next;
current.next = new Node(e);
(current.next).next = temp;
size++;
}
}
/** Remove the head node and
* return the object that is contained in the removed node. */
public E removeFirst() {
if (size == 0) {
return null;
}
else {
Node temp = head;
head = head.next;
size--;
if (head == null) {
tail = null;
}
return (E)temp.element;
}
}
/** Remove all elements from list */
public void removeAll() {
while(true) {
if (size == 0) {
break;
}
else {
Node temp = head;
head =.
Similar to Required to augment the authors Binary Search Tree (BST) code to .docx (20)
Ethical Case Study 2Gloria is a housekeeper in an independent li.docxdebishakespeare
Ethical Case Study 2
Gloria is a housekeeper in an independent living community. While walking through a hallway, she noticed the door of a resident’s apartment was left open, which was unusual. She stepped in to check on Louis, and quickly realized that he was on the phone in his living room. As she turned to leave, she over heard him saying that he had stopped taking all of his medications because he was ready to die. She could tell that the person that he was speaking with was trying to reason with him. Gloria knows that Louis has a very loving and involved daughter that visits him every Saturday. She left the room determined that she would tell his daughter what she heard when she saw her on Saturday.
You have to answer all the questions below
What issues are facing Gloria? Discuss the possible ethical principles at play and your recommendation to Gloria.
Hint: Confidentiality, Beneficence, Self-determination
.
Ethical consideration is important in nursing practice, especial.docxdebishakespeare
Ethical consideration is important in nursing practice, especially when providing care to patients from diverse sociocultural backgrounds. The population of the United States comprises various ethnic/racial groups with different cultural and social beliefs, practice, norms, and values. There is an increasing disparities on the incidence and prevalence of type 2 diabetes among different communities in the United States. According to the Center for Disease Control and Prevention (CDC), Hispanics and African Americans have the highest incidence and prevalence of type 2 diabetes in the country (Concha, Mayer, Mezuk, & Avula, 2016). Caring for patients from different ethnic/racial groups require consideration of ethical principles and concepts to prevent ethical issues that may arise during nurse-patient interaction.
Recently, I cared for patient with type 2 diabetes mellitus who had been hospitalized for more than two weeks due to acute hypertension, partial loss of vision. Also, the patient had a chronic diabetic foot ulcer. The analysis of his medical history revealed that the diabetic foot ulcer had developed in the last two years and had never healed. The patient was so worried about his health status and kept asking when he was going to be discharged from the hospital. The patient came from the Hispanic community, which is one of minority groups with the highest incidence and prevalence of type 2 diabetes mellitus in the country. Being a culturally competent registered nurse, I had an obligation to take into account the specific ethnic background of the patient when providing care. Considering patient’s ethnic/racial background is important in providing quality, holistic, and patient-centered care based their health concerns, preferences, and values (Concha et al., 2016).
When collecting subjective data for analysis and planning for the care. I asked the patient about his perceptions about the possible causes of type 2 diabetes that he was suffering from. Hispanics have different beliefs in the causation of diabetes mellitus (Frieden, 2016). First, the patient believed that diabetes is a temporary condition that is not fatal. Second, the patient narrated a story that attempts to identify the cause of diabetes and concluded that they believe that people with “good diabetes” do not experience a lot of complications. The Hispanics use the term “good diabetes” when referring to the type of diabetes that do not require insulin for therapeutic purposes; non-insulin-dependent diabetes mellitus (T2DM) (Frieden, 2016). Also, the patient had a fatalistic attitude and believed that his health condition is likely to be a punishment from God.
The patient had a low health literacy level because caregivers had encouraged him to engage in some physical exercise and adopt a self-management approach as a way of controlling and preventing complications related to his condition, but he never implemented them. Also, the pat.
Ethical Competency Writing Assignment Description
PHI 108 Spring 2019
Dr. David M. DiQuattro
March 5, 2019
1 Basic Assignment Description
For your ethical competency writing assignment, you will write analyze a disagreement between two authors/viewpoints
that we discussed this semester. I am calling the assignment a critical disagreement analysis. Below I will
provide a number of examples of disagreements between the authors we discuss this semester. Your
paper will have the following components
1. Hone the disagreement
• I want you to start by taking my general statement of disagreement and providing your own clear specifics
that focus on particular claims or passages. Here you are taking my starting point, but providing your
own framing of the disagreement that will provide focus for your paper.
• You will hone your statement of the disagreement in a way that sets things up for the next parts of the
paper.
• For example:
– In number 2 below, you will identify a specific critique of Rawls from either Kittay or Noddings.
You need to explain where the disagreement is and set the stage for a fruitful dialogue to follow in
the paper.
• This part of the paper should be focused. You should discuss the two views in a way that sets the stage
for your objection and response.
• In the opening part of the paper you need to preview what is ahead - you may only write this part late
in the writing process, but you need to provide a clear preview of where the rest of the paper goes.
2. Provide the best objection from one point of view to another
• I want you to do more than just state the two sides of the issue in this paper. I want you to bring the
authors into dialogue. You will do this by articulating an objection to one position from the point of
view of the other, then responding to the objection.
– You want your objection to be more than just restating a point where the authors diagree. Here’s
what I mean by just restating, as an example:
1
Kant believes that there are absolute rules that should be followed without regard to conse-
quences. The strongest utilitarian objection to this is that Kant disregards the importance
of how an action affects overall happiness.
– The above is an example of what not to do. That way of stating things won’t get you far because
it is just a re-stating of a key difference between Kant and utilitarianism.
• You should look for an objection that raises a new question for the other point of view, or points out
an unforeseen implication of the view. In some way it should move discussion forward. I am not
asking you to discover something that has never been said about these issues. I just want
you to deepen your understanding of the two views by raising a serious objection to one
position, then responding to it.
– In some way the objection should force you to think in new ways about the position objected to.
• In this section you should explain as clearly as you can how the objection presents a proble.
Ethical Case StudyAn example of unethical treatment of participa.docxdebishakespeare
Ethical Case Study
An example of unethical treatment of participants was the Tuskegee syphilis experiment, who believed they were being treated for “bad blood”
“Bad blood”: A term used to describe problems like anemia, fatigue, and syphilis
Those in the control group were not given treatment for syphilis, and many died
Why would this research study not fall under the present ethical and legal restraint? Please support your answer with scholarly articles.
.
Ethical AwarenessDEFINITION a brief definition of the k.docxdebishakespeare
Ethical Awareness
DEFINITION
:
a brief definition of the key term followed by the APA reference for the term; this does not count in the word requirement.
SUMMARY
:
Summarize the article in your own words- this should be in the
150-200 word range
. Be sure to note the article's author, note their credentials and why we should put any weight behind his/her opinions, research or findings regarding the key term.
DISCUSSION
:
Using
300-350 words
, write a brief discussion, in your own words of how the article relates to the selected chapter Key Term. A discussion is not rehashing what was already stated in the article, but the opportunity for you to
add value by sharing your experiences, thoughts, and opinions
.
This is the most important part of the assignment.
REFERENCES
:
All references must be listed at the bottom of the submission--in APA format.
Please follow the above format, No Plagiarism, APA format, add citations and references.
.
ETHICAL CHALLENGES
JOYCAROLYNE MUIGAI
NTC/302
5/26/2020
INTRODUCTION
Ethics in business is mainly concerned with the good or bad actions and behaviors that often take place in the world of business
Ethical challenges have often resulted from lack of a clear and distinctive description of norms that ought to be used
Business ethics hence help economists to think productively along moral dimensions on matters regarding policy problems
Ethics could be a complex aspect in business as it influences all aspect of business as it provides the most adequate action that ought to be taken. Ethics causes huge conflicts as morality may not be clearly definitive and situations in many cases greatly vary (Nuseir & Ghandour, 2019).
2
Ethics in intellectual property
Intellectual property rights is a socio-economic tool that create some form of monopoly for firms to charge a price for their innovations
For many innovative firms, it is a timely and expensive to come up with new innovations for the market yet other competitors in the market will attempt to copy new design of products launched.
Firms have however, taken advantage of intellectual property rights by asking for high prices for products
Intellectual property rights are a tool that protects innovators from losing their innovations to counter-feighting firms in the market. However many have leveraged this property rights to put high prices on their products to maximize their profits from their innovations (Sonderholm, 2018).
3
Policy statement on Ethics in intellectual property
To ensure easy and right access of new innovated products, it is important to come up with an ethical way to reduce exploitation by firms.
Firms can take up he differential pricing strategy that has in the past been articulated to be of great influence and guarantees the firm’s profitability
Through differentia; pricing, the protected innovation can be offered at different prices based on the socio-economic demographics of the area. A product can be offered at a cheaper price at a low-earning area while it is offered at different price at a different location (Sonderholm, 2018).
4
Corruption index
Corruption is seen as legal complication that is often manifested in the absence of controls over power
Corruption in business could come in many ways but it is always some grease payment paid to expedite decision or transactions
Connection are as well viewed as to have an effect on business processes as they have a negative connotation regardless of their informality.
In many business ventures, corruption has been indicated to grow over time and is often seen in terms of exchange of favors for the sake of expedition of certain process to take a shorter time without necessarily having to undergo the require stipulated process (Samuel, 2019).
5
Policy statement in corruption index
Transparency is key in business processes hence all actions need to be accounted for
As a way to reduce the corruption index and subsequ.
Ethical Conduct of Researchpower point from this document, 1.docxdebishakespeare
Ethical Conduct of Research
power point from this document, 15 slides
Introduction
Depending on the context of the study, researchers often encounter ethical dilemmas that are associated with respect for privacy, establishment of honest and open interactions, and avoidance of misrepresentation. From an ethical standpoint, such challenging circumstances may surface if researchers are grappling with conflicting issues and have to choose between different methodological approaches in complex circumstances. In such circumstances, disagreements among different components including participants, researchers, researchers’ disciplines, the financing organization, and the society might be inevitable. Therefore, there are numerous ethical concerns that should be taken into account when undertaking studies that deal with human subjects. Understanding ethical principles can guide researchers to conduct studies that safeguard the wellbeing of human subjects.
Overview of the Research
In a research work titled
Resilience of People Living with HIV/AIDS in Indonesia: a Phenomenological Study
, Kumboyono et al. (2018) observe that HIV/ AIDS is among the most prevalent and expanding communicable diseases on the planet. The number of individuals who are diagnosed with HIV/AIDS continues to skyrocket every year in Indonesia and other parts of the world. According to Kumboyono et al. (2018), individuals who suffer from HIV/AIDS often plunge themselves into a series of crises, which indicate the challenges of living with the chronic pathological condition. As such, resilience is one distinct phenomenon that is common among persons living with the diseases Indonesia, a pattern that indicates the results of current health management and expectations of HIV/AIDS patients for better and improved health outcomes. In light of this concern, Kumboyono et al. (2018) undertook a study that sought to examine the mechanism of resilience in Indonesian people living with HIV/AIDS and the factors that influence their specific mechanisms.
Using qualitative phenomenological design, the researchers sampled a total of 27 people living with HIV/AIDS from a primary health care institution in Malang City, East Java, Indonesia. The participants were selected from different socioeconomic, gender, and sexual orientations. The researchers informed participants about the conduct and processes involved in the study, resulting in their consent to participate in the interview process. The findings of the study indicated that the diagnosis of HIV/AIDS reflects the onset of psychological and social distress. Moreover, Kumbomoyo et al. (2018) found that the spiritual response that follows diagnosis is a state that is characterized by crises. As a consequence, the coping strategies and understanding of life by HIV patients is a definite sign on resilience. Based on these findings, Kumbomoyo et al. (2018) infer that HIV/AIDS is a chronic infection that has the potential to induce the unique .
Ethical Approaches
An Overview of:
(1)Consequential,
(2) Nonconsequential, and
(3) Virtue Ethics Theories
What is Ethics?
Ethics is the study of those values that relate to our moral conduct,
including questions of good and evil, right and wrong, and moral responsibility.
Consequentialist Theoretical Approach:
-Consequentialist theories claim that the morality of an action depends only on its consequences.
-It only considers the result of actions and not principles or rules in determining morality.
1
Three (3) Types of Consequentialist Theories:
-Ethical Egoism argues that each person should act in his/her own self-interest.
-Act Utilitarianism argues that each person should act in a way that produces the greatest happiness
for everyone.
-Rule Utilitarianism argues that each person should follow rules that tend to produce the greatest
happiness for everyone.
Weaknesses of Consequentialist Theories
-Requires person to predict the future and all possible outcomes.
-Can easily be used to justify questionable actions (the ends justifies the means).
2
Nonconsequentialist Theoretical Approach:
Nonconsequentialist theories claim that the morality of an action depends on principles or other factors
that are not related to consequences.
Two (2) Types of Nonconsequentialist Theories:
-Divine command theory argues that we should obey the laws of God.
-Kant’s Categorical Imperative states that we should always act in a way that is based on reason, duty,
and would be considered ethical if everyone acted in the exact same way. Also, people should be
treated as an end and not as a means.
Weaknesses of Nonconsequentialist Theories: Self-Challenge Question:
Question: What might prove a problem in a country so diverse as the U.S. with regards to
Nonconsequentialist theories?
When you are ready check the expert’s response.
3
https://kapextmediassl-a.akamaihd.net/business/CS125/1902c/ethics_challenge_expert1.pdf
Virtue Ethics Theoretical Approach:
-Virtue ethics seeks to identify character traits of a moral person and develop those with the idea that the
virtuous person will act in a virtuous manner. It does not look to principles or consequences.
-Virtue ethics was developed among the ancient Greek philosophers such as Aristotle and the Chinese
teacher and philosopher Confucius.
-Virtue ethics enjoys modern support as an approach that avoids many of the problems with
Consequential and Nonconsequential ethical theories.
Weaknesses of Virtue Theory
-Difficulty in determining just which characteristics are virtues
-Justification for respecting a virtue usually brings one back to either consequences or principles.
-Difficulty in applying it to specific situations
4
Example of all Three Theoretical Ethical Approaches:
Scenario: The air quality in a particular city Y is so polluted, people are getting physically ill and are on .
Ethical and Professional Issues in Group PracticeThose who seek .docxdebishakespeare
Ethical and Professional Issues in Group Practice
Those who seek to be professional group leaders must be willing to examine both their ethical standards and their level of competence. Among the ethical issues treated in this chapter are the rights of group members, including informed consent and confidentiality; the psychological risks of groups; personal relationships with clients; socializing among members; the impact of the group leader’s values; addressing spiritual and religious values of group members; working effectively and ethically with diverse clients; and the uses and misuses of group techniques. In my opinion, a central ethical issue in group work pertains to the group leader’s competence. Special attention is given to ways of determining competence, professional training standards, and adjuncts to academic preparation of group counselors. Also highlighted are ethical issues involved in training group workers. The final section outlines issues of legal liability and malpractice.
As a responsible group practitioner, you are challenged to clarify your thinking about the ethical and professional issues discussed in this chapter. Although you are obligated to be familiar with, and bound by, the ethics codes of your professional organization, many of these codes offer only general guidelines. You will need to learn how to make ethical decisions in practical situations. The ethics codes provide a general framework from which to operate, but you must apply these principles to concrete cases. The Association for Specialists in Group Work’s (2008) “Best Practice Guidelines” is reproduced in the Student Manual that accompanies this textbook. You may want to refer to these guidelines often, especially as you study Chapters 1 through 5.
The Rights of Group Participants
My experience has taught me that those who enter groups are frequently unaware both of their basic rights as participants and of their responsibilities. As a group leader, you are responsible for helping prospective members understand what their rights and responsibilities are. This section offers a detailed discussion of these issues.
A Basic Right: Informed Consent
If basic information about the group is discussed at the initial session, the participants are likely to be far more cooperative and active. A leader who does this as a matter of policy demonstrates honesty and respect for group members and fosters the trust necessary for members to be open and active. Such a leader has obtained the informed consent of the participants.
Informed consent is a process that begins with presenting basic information about group treatment to potential group members to enable them to make better decisions about whether or not to enter and how to participate in a group (Fallon, 2006). Members have a right to receive basic information before joining a group, and they have a right to expect certain other information during the course of the group. Discussing informed consent is not a one-t.
Ethical AnalysisSelect a work-related ethical scenario that .docxdebishakespeare
Ethical Analysis
Select a work-related ethical scenario that you (or someone close to you) have experienced. Organizations and names should be changed when identifying references in the assignment. Compose an essay that addresses the following requirements:
Identify the key positions, titles, and assigned responsibilities in the organization.
Discuss and illustrate the individual pressures faced and how the issues were handled or delegated to another position.
Describe how changing attitudes and behaviors evolved as the incidents occurred.
Compare and contrast the behaviors in the scenario with the philosophical theories of ethical decision-making that are referenced in Unit II. Examples may include Utilitarianism or Deontology application.
Illustrate any mishandling of the decision-making process that resulted in lessons learned.
Summarize what you have learned from an analysis of this event.
Your response should be at least 500 words in length (not including the references page) in APA style. You are required to use at least your textbook as source material for your response. All sources used, including the textbook, must be referenced; paraphrased and quoted material must have accompanying citation.
.
Ethical (Moral) RelativismIn America, many are comfortable describ.docxdebishakespeare
Ethical (Moral) Relativism
In America, many are comfortable describing ethics as follows: “Well, what’s right for me is right for me and what’s right for you is right for you. Let’s just agree to disagree.” This is an affirmation of what philosophers call
individual
or
subjective moral relativism
. In this understanding of relativism, morality is a matter of individual feelings and personal preference. In individual moral relativism, the determination of what is right and wrong in a situation varies according to the individual. Moral relativists do not believe in natural law or universal truths.
Cultural moral relativism
puts culture at the forefront of relative ethical decision-making. It says the individual must include the precepts of his or her culture as a prominent part of the relativistic moral action.
Lawrence
Kohlberg,
a prominent psychologist known for recognizing moral stages of development, takes it a step farther saying cultural relativists are persons stuck in the “
Conventional
Stage” of ethical development
.
In your paper, please define individual moral relativism and cultural moral relativism in detail, noting how they differ from each other, their strengths and weaknesses, and give your position on Kohlberg’s stance on ethical relativism.
What aspects of ethical relativism do you identify and agree with? What aspects do you disagree with? Give a personal example that illustrates your stance on ethical relativism, describing how you made a moral decision in an ethical dilemma. Include at least two references to support your thoughts.
Post a 500-word paper to the
M4: Assignment 2 Dropbox
by due
Wednesday, April 9, 2014
. All written assignments and responses should follow proper citation rules for attributing sources. Please use Microsoft Word spelling/grammar checker. Be mindful of plagiarism policies.
.
Ethical Analysis on Lehman Brothers financial crisis of 2008 , pleas.docxdebishakespeare
Ethical Analysis on Lehman Brothers financial crisis of 2008 , please include bibliography and footnotes and answer the questions below.
It must be between 5-7pgs.
1. What was the case about?
2. Who was (were) the individual(s) and company (ies) involved?
3. When did it happen?
4. Why did it happen?
5. How did it come to the attention of the media?
6. What was the outcome of the case?
7. How could this case been avoided?
8. What can we learn from the case?
.
Ethical Analysis on Merrill lynch financial crisis of 2008 , please .docxdebishakespeare
Ethical Analysis on Merrill lynch financial crisis of 2008 , please include bibliography and footnotes and aswer the questions below.
It must be between 5-7pgs.
1. What was the case about?
2. Who was (were) the individual(s) and company (ies) involved?
3. When did it happen?
4. Why did it happen?
5. How did it come to the attention of the media?
6. What was the outcome of the case?
7. How could this case been avoided?
8. What can we learn from the case?
.
ETHC 101
Discussion Board Reply Grading Rubric
Criteria
Levels of Achievement
Content 70%
Advanced
Proficient
Developing
Not Present
Points Earned
Word Count
15 points
Word count is between 500 and 600 words.
11 to 14 points
Word count exceeds 600 words.
1 to 10 points
Word count is less than 500 words.
0 points
Not present
Style
10 points
Reply offers constructive feedback to a classmate in a manner that is polite, rationally argued, and not overly emotional.
7 or 9 points
Reply offers constructive feedback to a classmate but with some deficiency of politeness, reasonableness, and/or dispassion.
1 to 6 points
Reply offers little to no constructive feedback, and/or is strongly impolite, and/or is very emotional.
0 points
The post is not a reply (it is off-topic).
Understanding
10 points
Reply utilizes many of the concepts and technical vocabulary taught in the class in a manner that demonstrates accurate understanding.
7 to 9 points
Reply utilizes some of the concepts and technical vocabulary taught in the class in a manner that demonstrates accurate understanding.
1 to 6 points
Reply utilizes some of the concepts and technical vocabulary taught in the class but sometimes in ways that suggest that they are not correctly understood.
0 points
Reply does not utilize the concepts and technical vocabulary taught in the class.
Structure 30%
Advanced
Proficient
Developing
Not Present
Points Earned
Spelling, Punctuation, and Grammar
10 points
Reply is written in paragraph form and is devoid of spelling, punctuation, and grammar errors.
7 or 9 points
Reply is not written in paragraph form and/or has occasional spelling, punctuation, and grammar errors.
1 to 6 points
Reply is not written in paragraph form and has numerous spelling, punctuation, and grammar problems.
0 points
Not present
Turabian formatting
5 points
Direct references and/or allusions to outside resources (such as the textbooks) are present and are cited using footnotes in current Turabian format.
4 points
Direct references and/or allusions to outside resources (such as the textbooks) are present but are cited otherwise than using footnotes in current Turabian format.
1 to 3 points
Direct references and/or allusions to outside resources (such as the textbooks) are present but the sources are not cited. (Note: if plagiarism is present, that requires additional corrective action.)
0 points
No direct references and/or allusions to outside resources are present.
Total
/50
Instructor's Comments:
Page 1 of 1
For this untimed, open-resource essay exam, answer each question thoroughly and clearly, and ground it in course reading material. Essay answers must be more than 3 or 4 brief sentences, but kept within the bounds of an essay exam (4 - 6 paragraphs). All your writing must be in your own words. Paraphrase (restate what you read) rather than copying material from the course textbook or the Internet. No copying is permitted in this course and doing so will result in zero points on th.
Ethical and Human Rights Concerns in Global HealthChapter Fou.docxdebishakespeare
Ethical and Human Rights Concerns in Global Health
Chapter Four
Chapter four: Ethical and human rights concerns in global health.
As with any area of health, global health is affected by the issues of ethics and right for sound health outcome. In this chapter we will explore ethical and human rights concerns, some of the central treaties and conversions related to human rights, some historically significant cases in human subject research and key principles for making critical decisions in health research.
1
Failure to respect human rights is often associated with harm to human health
Health research with human subjects puts people at risk for the sake of other people’s health
Health investments must be made in fair ways since resources are limited
The Importance of Ethical and Human Rights Issues in Global Health
Access to the health care is human right and failure to respect this right might causes harm for health. For example, the stigma associated with HIV, TB and leprosy makes it difficult for the patient to obtain necessary health care, it not only cause harm to individual health but as a whole community health even. For example, if a TB patient remains untreated by the health care workers, then that individual could be a source of infection for other people.
Health research with human subject in particular in low income countries where study participants may not have other option to obtain the medication might become a proxy of clinical trial for other people .Lastly, fair decision in health investment is critical because in low income countries where health resources are scare difficult decisions need to be made depending on the priority and severity of disease.
2
The Foundations for Health and Human Rights
Universal Declaration of Human Rights and other legally binding multilateral treaties
Governments are obliged to respect, protect, and fulfill the rights they state
International Bill of Human Rights is the cornerstone for human rights. This bill include couple of documents including the Universal declaration of human rights that was officially declared in 1948, that place obligation on Government to respect , protect, and fulfill the rights of the state.
3
Selected Human Rights
The Rights-Based Approach
Assess health policies, programs, and practices in terms of impact on human rights
Analyze and address the health impacts resulting from violations of human rights when considering ways to improve population health
Prioritize the fulfillment of human rights
In considering human right, first we are going to examine the issue of right based approach. Some global health advocates argue that this approach, which thinks that fulfillment of people’s human right is conducive to their health, should be followed in global health. This means we need to assess health policies, programs or practices in terms of its impact on human right and analyze the health impacts from the perspective of violation of human rights
.
Ethical & Legal Aspects in Nursing WK 14Please answer the .docxdebishakespeare
Ethical & Legal Aspects in Nursing WK 14
Please answer the following Discussion Question. Please be certain to answer the four questions on this week DQ and to provide a well-developed and complete answer to receive credit.
Case Study, Chapter 23, Professional Identity and Image
Nursing care is frequently perceived by the public as simple and unskilled. Many male nurses live in fear of how their caring actions might be interpreted. Many nurses hold that stereotypes about the profession are true, just as the general public does. Public identity and image has been a struggle for nurses for a long time. The greater public clearly does not understand what professional nursing is all about, and the nursing profession has done a poor job of correcting long-standing, historically inaccurate stereotypes.
1. What are the common nursing stereotypes?
2. What was the role of the Center for Nursing Advocacy? Discuss the role of Truth about Nursing in addressing inaccurate or negative portrayals of nursing in the media and the process they use to raise public and professional awareness of the issues surrounding nursing public image?
3. What are some of the ways of changing nursing’s image in the public eye?
4. One of the most important strategies needed to change nursing’s image is to change the image of nursing in the mind of the image makers. What are some of the key ways for nurses to interact with the media?
INSTRUCTIONS:
APA FORMAT
IN TEXT CITATIONS WITH 3 REFERENCES NO LESS THAN 5 YEARS
.
EthernetSatellite dishInternational Plastics, Inc. - C.docxdebishakespeare
Ethernet
Satellite dish
�
International Plastics, Inc. - China Headquarters
Corp
Marketing
Finance
HR
R&D
Network
MAC
PRO
(15)
Dual 1.8 GB
1 Ghz 6 core
12 GB Ram
1 TB HD
27" monitors
Satellite base station
NAS
Iomega
P800M
24 Port Hub
Linksys EF2H24
WIN
Exchange
Server
WIN
Network
Server
UNIX
ERP/MRP
Server
ERP = SAP
UPS:
Serve the entire server room; additional UPS in satellite base station.
IBM
pSeries
6E4 Multipocessor
16GB RAM
1 TB HD
2 ea IBM
HS20
Blade Svrs
2 X XEON
2.8 GHz
1 GB RAM
1 GB Fiber backbone
3 ea Phaser 6700 color Printers
100 base T
35 ea Dell
Vostro
i3 3.3 Ghz
4 GB RAM
500 GB HD
WIN 7 OS
Office 2007
12
8
8
7
2 ea 24 port switches
Cisco 2950
35 IP
Phones
Gateway/Switch
1 HP Plotter
Identical to other WIN servers
VOIP/Data
Router
T3 to
outside network
Gateway/Switch
VOIP/Data
Router
Ka Band
ATM AA1 PVC 51.8 Mb data rate, AES end-to-end
8 HP Laserjet BW printers – P3015dn
2 in each department
Ethernet
Satellite dish
�
International Plastics, Inc. - Corporate Headquarters
Corp
Marketing
Finance
HR
R&D
Network
MAC
PRO
(15)
Dual 1.8 GB
1 Ghz 6 core
12 GB Ram
1 TB HD
27" monitors
Satellite base station
NAS
Iomega
P800M
24 Port Hub
Linksys EF2H24
WIN
Exchange
Server
WIN
Network
Server
UNIX
ERP/MRP
Server
ERP = SAP
UPS:
Serve the entire server room; additional UPS in satellite base station.
IBM
pSeries
6E4 Multipocessor
16GB RAM
1 TB HD
2 ea IBM
HS20
Blade Svrs
2 X XEON
2.8 GHz
1 GB RAM
1 GB Fiber backbone
3 ea Phaser 6700 color Printers
100 base T
35 ea Dell
Vostro
i3 3.3 Ghz
4 GB MB RAM
GB HD
WIN 7 OS
Office 2007
12
8
8
7
2 ea 24 port switches
Cisco 2950
35 IP
Phones
Gateway/Switch
1 HP Plotter
Identical to other WIN servers
VOIP/Data
Router
T3 to
outside network
Gateway/Switch
VOIP/Data
Router
Ka Band
ATM AA1 PVC 51.8 Mb data rate, AES end-to-end
8 HP Laserjet BW P4510 Printers: 2 in each department.
2 HP color Multifunction Office Jet 8600. 1 in corporate, 1 in marketing
Ethernet
�
�
�
�
�
Disk array
�
No symbols exist on the page to display.�
Legend�
Legend Subtitle�
Symbol�
Count�
Description�
Cisco Router
2900
T-2 connection to corporate
UPS
HP Laserjet Pro MFN
M425dn
NAS Disk array
Cat 5 cable
45 client computers with Windows 7 and MS office 2007
4 Network Printers
Cat 5 cabling in building
45 office computers
Dell Vostro
I3 3.3 GHz
4 GB RAM
500 MB HD
Manufacturing
Floor
48 Port patch panels
Connection to
Corp.
Fiber link for NAS
2 - HP Laserjet M602n
HP CP4225n
Color Laser Printer
Blade Server
HP – BL 460 P
Print, file, Exchange, local ERP back to home office
Cisco Catylst 3580 Ethernet switch 48 port
Cisco catalyst 3560
Ethernet switch 24 port
APC Smart-UPS
5000 VA USB & Serial 220VAC
International Plastics, Inc.
Pontiac, MI Network Diagram
Ethernet
Disk array
Link builder
Firewall
Cisco Router
2900
Fiber link for NAS
24 port
100 Mbps Switches
NAS Disk array
T 2 connection to corporate
2.
Ethanolv.DrizinUnited States District Court, N.D. Iowa, Eastern .docxdebishakespeare
Ethanolv.Drizin
United States District Court, N.D. Iowa, Eastern DivisionFeb 7, 2006
No. C03-2021 (N.D. Iowa Feb. 7, 2006) Copy Citation
No. C03-2021.
February 7, 2006
Be a better lawyer. Casetext is legal research for lawyers who want do their best work.
ORDER
JOHN JARVEY, Magistrate Judge
This matter comes before the court pursuant to trial on the merits which commenced on January 23, 2006. The above-described parties have consented to jurisdiction before a United States Magistrate Judge pursuant to 28 U.S.C. § 636(c). The court finds in favor of the plaintiff and awards compensatory damages in the amount of $3,800,000 and punitive damages in the amount of $7,600,000.
In this case, the plaintiff brings numerous theories of recovery against defendant Jerry Drizin arising out of the misappropriation of escrow funds that were to serve as security for financing for the construction of an ethanol plant in Manchester, Iowa. The plaintiff contends that defendant Drizin, in concert with others, knowingly converted funds from an escrow account that were not to have been spent on anything without the plaintiff's prior written permission. Defendant Drizin contends that his only client and only duty of loyalty was to a Nigerian citizen living in Munich who caused the funds to be sent to bank accounts controlled by Defendant Drizin. The court makes the following findings of fact and conclusions of law.
In 2000 in Manchester, Iowa, farmer and President of the local Co-op, Douglas Bishop, began meeting with representatives of the United States Department of Agriculture to explore the feasibility of building an ethanol plant in the Manchester area. The idea was to assist farmers in the area in getting more value for their crops. An ethanol plant produces ethanol and feed grain which can be sold at a profit exceeding that associated with the mere sale of grain.
A series of 40 local meetings culminated in a membership drive. The Plaintiff, Northeast Iowa Ethanol, L.L.C., was later formed in order to sell 2500 shares of stock in the L.L.C. to raise funds for the financing of the plant. The construction of the plant was expected to cost $21 Million. It would have a capacity for producing 15 million gallons of ethanol per year. Through the meetings, Mr. Bishop and others raised $2,365,000. The average investor purchased two shares.
The membership drive ended in September 2001. The original plan was to begin construction in the fall of 2001 and have the plant operating by the fall of 2002. However, the issue of financing for the plant was more problematic than plaintiff had anticipated. Traditional lenders (banks) demanded that the plaintiff raise forty percent of the construction costs. It was clear that the plaintiff could not raise $8 Million. Plaintiff's proposed marketing partner, Williams Ethanol Services, agreed to invest $1 Million in the project. The contractor anticipated to build the facility, North Central Construction from North Dakota,.
Read| The latest issue of The Challenger is here! We are thrilled to announce that our school paper has qualified for the NATIONAL SCHOOLS PRESS CONFERENCE (NSPC) 2024. Thank you for your unwavering support and trust. Dive into the stories that made us stand out!
A Strategic Approach: GenAI in EducationPeter Windle
Artificial Intelligence (AI) technologies such as Generative AI, Image Generators and Large Language Models have had a dramatic impact on teaching, learning and assessment over the past 18 months. The most immediate threat AI posed was to Academic Integrity with Higher Education Institutes (HEIs) focusing their efforts on combating the use of GenAI in assessment. Guidelines were developed for staff and students, policies put in place too. Innovative educators have forged paths in the use of Generative AI for teaching, learning and assessments leading to pockets of transformation springing up across HEIs, often with little or no top-down guidance, support or direction.
This Gasta posits a strategic approach to integrating AI into HEIs to prepare staff, students and the curriculum for an evolving world and workplace. We will highlight the advantages of working with these technologies beyond the realm of teaching, learning and assessment by considering prompt engineering skills, industry impact, curriculum changes, and the need for staff upskilling. In contrast, not engaging strategically with Generative AI poses risks, including falling behind peers, missed opportunities and failing to ensure our graduates remain employable. The rapid evolution of AI technologies necessitates a proactive and strategic approach if we are to remain relevant.
Francesca Gottschalk - How can education support child empowerment.pptxEduSkills OECD
Francesca Gottschalk from the OECD’s Centre for Educational Research and Innovation presents at the Ask an Expert Webinar: How can education support child empowerment?
The French Revolution, which began in 1789, was a period of radical social and political upheaval in France. It marked the decline of absolute monarchies, the rise of secular and democratic republics, and the eventual rise of Napoleon Bonaparte. This revolutionary period is crucial in understanding the transition from feudalism to modernity in Europe.
For more information, visit-www.vavaclasses.com
2024.06.01 Introducing a competency framework for languag learning materials ...Sandy Millin
http://sandymillin.wordpress.com/iateflwebinar2024
Published classroom materials form the basis of syllabuses, drive teacher professional development, and have a potentially huge influence on learners, teachers and education systems. All teachers also create their own materials, whether a few sentences on a blackboard, a highly-structured fully-realised online course, or anything in between. Despite this, the knowledge and skills needed to create effective language learning materials are rarely part of teacher training, and are mostly learnt by trial and error.
Knowledge and skills frameworks, generally called competency frameworks, for ELT teachers, trainers and managers have existed for a few years now. However, until I created one for my MA dissertation, there wasn’t one drawing together what we need to know and do to be able to effectively produce language learning materials.
This webinar will introduce you to my framework, highlighting the key competencies I identified from my research. It will also show how anybody involved in language teaching (any language, not just English!), teacher training, managing schools or developing language learning materials can benefit from using the framework.
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdfTechSoup
In this webinar you will learn how your organization can access TechSoup's wide variety of product discount and donation programs. From hardware to software, we'll give you a tour of the tools available to help your nonprofit with productivity, collaboration, financial management, donor tracking, security, and more.
Honest Reviews of Tim Han LMA Course Program.pptxtimhan337
Personal development courses are widely available today, with each one promising life-changing outcomes. Tim Han’s Life Mastery Achievers (LMA) Course has drawn a lot of interest. In addition to offering my frank assessment of Success Insider’s LMA Course, this piece examines the course’s effects via a variety of Tim Han LMA course reviews and Success Insider comments.
Macroeconomics- Movie Location
This will be used as part of your Personal Professional Portfolio once graded.
Objective:
Prepare a presentation or a paper using research, basic comparative analysis, data organization and application of economic information. You will make an informed assessment of an economic climate outside of the United States to accomplish an entertainment industry objective.
Introduction to AI for Nonprofits with Tapp NetworkTechSoup
Dive into the world of AI! Experts Jon Hill and Tareq Monaur will guide you through AI's role in enhancing nonprofit websites and basic marketing strategies, making it easy to understand and apply.
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...Levi Shapiro
Letter from the Congress of the United States regarding Anti-Semitism sent June 3rd to MIT President Sally Kornbluth, MIT Corp Chair, Mark Gorenberg
Dear Dr. Kornbluth and Mr. Gorenberg,
The US House of Representatives is deeply concerned by ongoing and pervasive acts of antisemitic
harassment and intimidation at the Massachusetts Institute of Technology (MIT). Failing to act decisively to ensure a safe learning environment for all students would be a grave dereliction of your responsibilities as President of MIT and Chair of the MIT Corporation.
This Congress will not stand idly by and allow an environment hostile to Jewish students to persist. The House believes that your institution is in violation of Title VI of the Civil Rights Act, and the inability or
unwillingness to rectify this violation through action requires accountability.
Postsecondary education is a unique opportunity for students to learn and have their ideas and beliefs challenged. However, universities receiving hundreds of millions of federal funds annually have denied
students that opportunity and have been hijacked to become venues for the promotion of terrorism, antisemitic harassment and intimidation, unlawful encampments, and in some cases, assaults and riots.
The House of Representatives will not countenance the use of federal funds to indoctrinate students into hateful, antisemitic, anti-American supporters of terrorism. Investigations into campus antisemitism by the Committee on Education and the Workforce and the Committee on Ways and Means have been expanded into a Congress-wide probe across all relevant jurisdictions to address this national crisis. The undersigned Committees will conduct oversight into the use of federal funds at MIT and its learning environment under authorities granted to each Committee.
• The Committee on Education and the Workforce has been investigating your institution since December 7, 2023. The Committee has broad jurisdiction over postsecondary education, including its compliance with Title VI of the Civil Rights Act, campus safety concerns over disruptions to the learning environment, and the awarding of federal student aid under the Higher Education Act.
• The Committee on Oversight and Accountability is investigating the sources of funding and other support flowing to groups espousing pro-Hamas propaganda and engaged in antisemitic harassment and intimidation of students. The Committee on Oversight and Accountability is the principal oversight committee of the US House of Representatives and has broad authority to investigate “any matter” at “any time” under House Rule X.
• The Committee on Ways and Means has been investigating several universities since November 15, 2023, when the Committee held a hearing entitled From Ivory Towers to Dark Corners: Investigating the Nexus Between Antisemitism, Tax-Exempt Universities, and Terror Financing. The Committee followed the hearing with letters to those institutions on January 10, 202
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
Required to augment the authors Binary Search Tree (BST) code to .docx
1. Required to augment the author's Binary Search Tree (BST)
code to support these new operations. Method names below are
merely suggestions. (The author’s class is attached separately in
the file called “authordoc”. I just built a simple test tree in the
author’s main method which can be used to test the various
operations. )
1. AnyType nthElement(int n) -- returns the n-th element
(starting from 1) of the in-order traversal of the BST.
2. int rank( AnyType x ) -- returns the "rank" of x. The rank of
an element is its position (starting with 1) in an in-order
traversal.
3. AnyType median( ) -- returns the median (middle) element in
the BST. If the BST contains an even number of elements,
returns the smaller of the two medians.
4. boolean isPerfect( ) -- returns true if the BST is a perfect
binary tree.
5. boolean isComplete( ) -- returns true if the BST is a complete
binary tree.
6. String toString( int nrLevels ) -- generates the level-order
output described in the sample output below.
Most of these operations could easily be implemented by
performing an in-order traversal inside the BST and perhaps
placing the results in an ArrayList. However, such a method is
extremely inefficient. Instead, we are going to achieve faster
performance by "augmenting" the BST nodes. You will add a
new private integer data member ("tree size") to the BinaryNode
which stores the size of the tree rooted at that node (including
the root). You must develop your own algorithms for these
operations, but obviously you will use the new tree size data
member to guide your search. Think before you code and think
recursively!
These items cover those topics not addressed elsewhere in the
project description. (R) indicates a requirement, (H) indicates a
2. hint, and (N) indicates a note.
1. (R) Although we are only using the BST for integers, the BST
must remain a generic class.
2. (R) Duplicate values are not allowed. Attempts to insert a
duplicate value should be ignored.
3. (R) Attempts to remove non-existent values should be
ignored.
4. (R) From a coding perspective, the easiest way to avoid
duplicate insertions or attempting to remove non-existent
elements is to first call find( ). However, this technique is NOT
permitted for two reasons.
Calling find( ) before each insert/remove doubles the running
time for these operations and is therefore inefficient.
Recusively coding the insert/remove methods to handle these
situations is a great learning experience.
5. (R) The level order print (PRINT command) outputs the
value of each node, the size of the tree rooted at that node, and
the value of the node's parent in that order, inside parenthesis,
separated by commas. (node value, tree size, parent value).
Since the root has no parent, print NULL for the root's parent
value. For readability, separate the levels with a blank line and
print no more than 6 node/size/parent values per line. If a level
requires multiple lines, use consecutive lines (without a blank
line between them).
6. (R) Efficieny counts! Use the most efficient algorithm
possible In particular, don't make multiple searches in the tree
when one will do. (Yes, we know it doesn't matter from an
asymptotic analysis point of view.)
7. (H) Almost all of these operations should be written
recursively, but not necessarily all of them.
8. (N) As is customary, your BST class should not provide any
methods for printing. However, the BST can provide a method
that formats a string containing information that the user wishes
to print. Overloading the toString( ) method is a common
technique to achieve this kind of functionality.
3. Note: The instructor noted that once the tree is built, it will not
be changed during testing of the program. (just to simplify the
task if that helps)
package Ast.rt;
import java.util.ArrayList;
// BinarySearchTree class
//
// CONSTRUCTION: with no initializer
//
// ******************PUBLIC
OPERATIONS*********************
// void insert( x ) --> Insert x
// void remove( x ) --> Remove x
// boolean contains( x ) --> Return true if x is present
// Comparable findMin( ) --> Return smallest item
4. // Comparable findMax( ) --> Return largest item
// boolean isEmpty( ) --> Return true if empty; else false
// void makeEmpty( ) --> Remove all items
// void printTree( ) --> Print tree in sorted order
//
******************ERRORS***************************
*****
// Throws UnderflowException as appropriate
/**
* Implements an unbalanced binary search tree.
* Note that all "matching" is based on the compareTo method.
* @author Mark Allen Weiss
*/
public class BinarySearchTree<AnyType extends Comparable<?
super AnyType>>
{
/**
* Construct the tree.
*/
5. public BinarySearchTree( )
{
root = null;
}
/**
* Insert into the tree; duplicates are ignored.
* @param x the item to insert.
*/
public void insert( AnyType x )
{
root = insert( x, root );
}
/**
* Remove from the tree. Nothing is done if x is not found.
* @param x the item to remove.
*/
6. public void remove( AnyType x )
{
root = remove( x, root );
}
/**
* Find the smallest item in the tree.
* @return smallest item or null if empty.
* @throws Exception
*/
public AnyType findMin( ) throws Exception
{
if( isEmpty( ) )
throw new Exception( );
return findMin( root ).element;
7. }
/**
* Find the largest item in the tree.
* @return the largest item of null if empty.
* @throws Exception
*/
public AnyType findMax( ) throws Exception
{
if( isEmpty( ) )
throw new Exception( );
return findMax( root ).element;
}
/**
* Find an item in the tree.
* @param x the item to search for.
* @return true if not found.
8. */
public boolean contains( AnyType x )
{
return contains( x, root );
}
/**
* Make the tree logically empty.
*/
public void makeEmpty( )
{
root = null;
}
/**
* Test if the tree is logically empty.
* @return true if empty, false otherwise.
*/
9. public boolean isEmpty( )
{
return root == null;
}
/**
* Print the tree contents in sorted order.
*/
public void printTree( )
{
if( isEmpty( ) )
System.out.println( "Empty tree" );
else
printTree( root );
}
/**
* Internal method to insert into a subtree.
10. * @param x the item to insert.
* @param t the node that roots the subtree.
* @return the new root of the subtree.
*/
private BinaryNode<AnyType> insert( AnyType x,
BinaryNode<AnyType> t )
{
if( t == null )
return new BinaryNode<AnyType>( x, null, null);
int compareResult = x.compareTo( t.element );
if( compareResult < 0 ){
t.left = insert( x, t.left );
}
else if( compareResult > 0 ){
t.right = insert( x, t.right );
11. }
else
; // Duplicate; do nothing
return t;
}
/**
* Internal method to remove from a subtree.
* @param x the item to remove.
* @param t the node that roots the subtree.
* @return the new root of the subtree.
*/
private BinaryNode<AnyType> remove( AnyType x,
BinaryNode<AnyType> t )
{
if( t == null )
return t; // Item not found; do nothing
int compareResult = x.compareTo( t.element );
12. if( compareResult < 0 )
t.left = remove( x, t.left );
else if( compareResult > 0 )
t.right = remove( x, t.right );
else if( t.left != null && t.right != null ) // Two children
{
t.element = findMin( t.right ).element;
t.right = remove( t.element, t.right );
}
else
t = ( t.left != null ) ? t.left : t.right;
return t;
}
/**
* Internal method to find the smallest item in a subtree.
* @param t the node that roots the subtree.
13. * @return node containing the smallest item.
*/
private BinaryNode<AnyType> findMin(
BinaryNode<AnyType> t )
{
if( t == null )
return null;
else if( t.left == null )
return t;
return findMin( t.left );
}
/**
* Internal method to find the largest item in a subtree.
* @param t the node that roots the subtree.
* @return node containing the largest item.
*/
private BinaryNode<AnyType> findMax(
BinaryNode<AnyType> t )
14. {
if( t != null )
while( t.right != null )
t = t.right;
return t;
}
/**
* Internal method to find an item in a subtree.
* @param x is item to search for.
* @param t the node that roots the subtree.
* @return node containing the matched item.
*/
private boolean contains( AnyType x,
BinaryNode<AnyType> t )
{
15. if( t == null )
return false;
int compareResult = x.compareTo( t.element );
if( compareResult < 0 )
return contains( x, t.left );
else if( compareResult > 0 )
return contains( x, t.right );
else
return true; // Match
}
/**
* Internal method to print a subtree in sorted order.
* @param t the node that roots the subtree.
*/
private void printTree( BinaryNode<AnyType> t )
16. {
if( t != null )
{
printTree( t.left );
System.out.println( t.element );
printTree( t.right );
}
}
/**
* Internal method to compute height of a subtree.
* @param t the node that roots the subtree.
*/
private int height( BinaryNode<AnyType> t )
{
if( t == null )
return -1;
else
18. right = rt;
}
AnyType element; // The data in the node
BinaryNode<AnyType> left; // Left child
BinaryNode<AnyType> right; // Right child
int treeSize;
}
/** The tree root. */
private BinaryNode<AnyType> root;
19. // Test program
public static void main( String [ ] args ) throws Exception
{
BinarySearchTree<Integer> t = new
BinarySearchTree<Integer>( );
int[] nums = new int[] {55, 40, 60, 30, 45, 70, 20, 35, 44,
47, 66, 80, 3, 36, 37, 43, 48, 65, 67, 77, 90};
for(int i = 0; i < nums.length; i++)
t.insert(nums[i]);
t.printTree();
System.out.println( "Checking... (no more output means
success)" );