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 ...
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 ...
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)
{
// -----------------------------------------------------------------------
...
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 == .
files/Heap.h
#ifndef HEAP_H
#define HEAP_H
#include <vector>
#include <stdexcept> // std::out_of_range
#include <math.h> // pow()
using namespace std;
template<typename T>
class Heap
{
private:
vector<T> _items; // Main vector of elements for heap storage
/**
* Used to take unsorted data and heapify it
*/
void buildHeap()
{
for (int i = _items.size() / 2; i >= 0; i--)
{
percolateDown(i);
}
}
/*********************************************************************/
/********************* Microassignment zone *************************/
/**
* Percolates the item specified at by index down
* into its proper location within a heap.
* Used for dequeue operations and array to heap conversions
* MA TODO: Implement percolateDown!
*/
void percolateDown(int index)
{
}
/**
* Percolate up from a given index to fix heap property
* Used in inserting new nodes into the heap
* MA TODO: Implement percolateUp
*/
void percolateUp( int current_position )
{
}
/************************** Microassigment zone DONE *********************/
public:
/**
* Default empty constructor
*/
Heap()
{
}
/**
* Constructor with a vector of elements
*/
Heap(const vector<T> &unsorted)
{
for (int i = 0; i < unsorted.size(); i++)
{
_items.push_back(unsorted[i]);
}
buildHeap();
}
/**
* Adds a new item to the heap
*/
void insert(T item)
{
int current_position = size(); // Get index location
_items.push_back(item); // Add data to end
percolateUp( current_position ); // Adjust up, as needed
}
/**
* Returns the top-most item in our heap without
* actually removing the item from the heap
*/
T& getFirst()
{
if( size() > 0 )
return _items[0];
else
throw std::out_of_range("No elements in Heap.");
}
/**
* Removes minimum value from heap and returns it to the caller
*/
T deleteMin()
{
int last_index = size() - 1; // Calc last item index
int root_index = 0; // Root index (for readability)
T min_item = _items[root_index]; // Keep item to return
_items[root_index] = _items[last_index]; // Move last item to root
_items.erase(_items.end() - 1); // Erase last element entry
percolateDown(0); // Fix heap property
return min_item;
}
/**
* Returns true if heap is empty, else false
*/
bool isEmpty() const
{
return _items.size() == 0;
}
/**
* Returns current quantity of elements in heap (N)
*/
int size() const
{
return _items.size();
}
/**
* Return heap data in order from the _items vector
*/
string to_s() const
{
string ret = "";
for(int i = 0; i < _items.size(); i++)
{
ret += to_string(_items[i]) + " ";
}
return ret;
}
/**
...
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.
Write a program in Java to implement the ADT Binary Tree part of who.docxrochellwa9f
Write a program in Java to implement the ADT Binary Tree part of whose definition is given below. You are also to write a driver program that demonstrates the correctness of your implementation by way of taking a series of commands from a text file and carrying them out. In each binary tree that you will deal with, the values are distinct (i.e. there are no duplicates).
Note: Code for binary tree that I discussed in class is available on Isidore. Feel free to use it but you will assume responsibility for the correctness.
The ADT Binary Tree
The only (private) data member you can use is root, as given below. However, feel free to use as many private member functions as you need.
/* Class BinaryTree */
public class BinaryTree> {
/* Class BinaryNode */
static private class BinaryNode> {
T
BinaryNode
BinaryNode
element; // data part
left; // left child
right; // right child
// Add appropriate constructors for BinaryNode
} // end of BinaryNode
private BinaryNode root; // root of the tree
private final int LCHILD = 1; // constant for left child
private final int RCHILD = 2; // constant for right child
// constructor for BinaryTree
public BinaryTree() {
root = null; // construct an empty tree
}
// Below are the methods that you must implement
//
// Create a tree with the given item as the root with its
// subtrees being empty.
// Post: Previous value of the tree is lost.
//
public void insertRoot (T item)
// If node containing parent exists, and if the specified // child is absent, create the specified child of parent // with item as data element and return true; otherwise
// return false.
//
// Pre: data items in the tree are distinct, i.e., no
duplicates.
// item, if it can be successfully inserted, is
different from
// each value in the tree.
// Post: if insertion were successful, item is the specified
child of
// parent.
// Parameters:
// item: data item to be inserted
// parent: data item of the potential parent // child == 1 => item is to be inserted as left
child of parent
// child == 2 => item is to be inserted as right
child of parent
// Return Value:
// true, if insertion succeeded, and false
otherwise.
public boolean insertItem (T item, T parent, int child)
// Print the tree contents in inorder to the stream
// associated with the printwriter output
public void printTree(PrintWriter output)
// Returns true if val1 exists, val2 exists, and they are
// siblings; otherwise, returns false
public boolean siblings (T val1, T val2)
// print to the given printwriter the frontier of the tree, // i.e., all the leaves in a "right to left reading of the // leaves” order; consecutive items are separated by a space public void printFrontier (PrintWriter output)
// delete subtree rooted at item, if item is present;
// otherwise, tree remains unchanged
public void deleteSubtree (T item)
// Post: if item is present, returns refer.
Please write in C++ and should be able to compile and debug.Thank yo.pdfajaycosmeticslg
Please write in C++ and should be able to compile and debug.Thank you
Create a class called BinaryTreeDeque. This binary tree implements all of the functionality of
the BinaryTree class, but instead of storing its values in a tree structure, the element values are
stored in a deque, using pointers to maintain the relationship between the binary tree and its node
values. Additionally: deque * getValues() - returns a copy of the deque the current array of
values (which should be in insertion order).
Solution
Following are steps to insert a new node in Complete Binary Tree.
1. If the tree is empty, initialize the root with new node.
2. Else, get the front node of the queue.
…….If the left child of this front node doesn’t exist, set the left child as the new node.
…….else if the right child of this front node doesn’t exist, set the right child as the new node.
3. If the front node has both the left child and right child, Dequeue() it.
4. Enqueue() the new node.
Code :-
-------------------------
binarytreedequeue.h
#ifndef BINARYTREEDEQUE_H
#define BINARYTREEDEQUE_H
// Program for linked implementation of complete binary tree
#include
#include
// For Queue Size
#define SIZE 50
// A tree node
struct node
{
int data;
struct node *right,*left;
};
// A queue node
struct Queue
{
int front, rear;
int size;
struct node* *array;
};
class BinaryTreeDeque
{
public:
BinaryTreeDeque();
struct node* newNode(int data);
struct Queue* createQueue(int size);
int isEmpty(struct Queue* queue);
int isFull(struct Queue* queue);
int hasOnlyOneItem(struct Queue* queue);
void Enqueue(struct node *root, struct Queue* queue);
struct node* Dequeue(struct Queue* queue);
struct node* getFront(struct Queue* queue);
int hasBothChild(struct node* temp);
void insert(struct node **root, int data, struct Queue* queue);
void display(struct Queue* queue);
node * getValues(struct Queue* queue);
};
#endif // BINARYTREEDEQUE_H
binarydequeue.cpp
---------------------------------------
#include \"binarytreedeque.h\"
BinaryTreeDeque::BinaryTreeDeque()
{
}
// A utility function to create a new tree node
struct node* BinaryTreeDeque::newNode(int data)
{
struct node* temp = (struct node*) malloc(sizeof( struct node ));
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
// A utility function to create a new Queue
struct Queue* BinaryTreeDeque::createQueue(int size)
{
struct Queue* queue = (struct Queue*) malloc(sizeof( struct Queue ));
queue->front = queue->rear = -1;
queue->size = size;
queue->array = (struct node**) malloc(queue->size * sizeof( struct node* ));
int i;
for (i = 0; i < size; ++i)
queue->array[i] = NULL;
return queue;
}
// Standard Queue Functions
int BinaryTreeDeque::isEmpty(struct Queue* queue)
{
return queue->front == -1;
}
int BinaryTreeDeque::isFull(struct Queue* queue)
{ return queue->rear == queue->size - 1; }
int BinaryTreeDeque::hasOnlyOneItem(struct Queue* queue)
{ return queue->front == queue->rear; }
void BinaryTreeDeque::Enqueue(struct node *root, s.
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 ...
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)
{
// -----------------------------------------------------------------------
...
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 == .
files/Heap.h
#ifndef HEAP_H
#define HEAP_H
#include <vector>
#include <stdexcept> // std::out_of_range
#include <math.h> // pow()
using namespace std;
template<typename T>
class Heap
{
private:
vector<T> _items; // Main vector of elements for heap storage
/**
* Used to take unsorted data and heapify it
*/
void buildHeap()
{
for (int i = _items.size() / 2; i >= 0; i--)
{
percolateDown(i);
}
}
/*********************************************************************/
/********************* Microassignment zone *************************/
/**
* Percolates the item specified at by index down
* into its proper location within a heap.
* Used for dequeue operations and array to heap conversions
* MA TODO: Implement percolateDown!
*/
void percolateDown(int index)
{
}
/**
* Percolate up from a given index to fix heap property
* Used in inserting new nodes into the heap
* MA TODO: Implement percolateUp
*/
void percolateUp( int current_position )
{
}
/************************** Microassigment zone DONE *********************/
public:
/**
* Default empty constructor
*/
Heap()
{
}
/**
* Constructor with a vector of elements
*/
Heap(const vector<T> &unsorted)
{
for (int i = 0; i < unsorted.size(); i++)
{
_items.push_back(unsorted[i]);
}
buildHeap();
}
/**
* Adds a new item to the heap
*/
void insert(T item)
{
int current_position = size(); // Get index location
_items.push_back(item); // Add data to end
percolateUp( current_position ); // Adjust up, as needed
}
/**
* Returns the top-most item in our heap without
* actually removing the item from the heap
*/
T& getFirst()
{
if( size() > 0 )
return _items[0];
else
throw std::out_of_range("No elements in Heap.");
}
/**
* Removes minimum value from heap and returns it to the caller
*/
T deleteMin()
{
int last_index = size() - 1; // Calc last item index
int root_index = 0; // Root index (for readability)
T min_item = _items[root_index]; // Keep item to return
_items[root_index] = _items[last_index]; // Move last item to root
_items.erase(_items.end() - 1); // Erase last element entry
percolateDown(0); // Fix heap property
return min_item;
}
/**
* Returns true if heap is empty, else false
*/
bool isEmpty() const
{
return _items.size() == 0;
}
/**
* Returns current quantity of elements in heap (N)
*/
int size() const
{
return _items.size();
}
/**
* Return heap data in order from the _items vector
*/
string to_s() const
{
string ret = "";
for(int i = 0; i < _items.size(); i++)
{
ret += to_string(_items[i]) + " ";
}
return ret;
}
/**
...
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.
Write a program in Java to implement the ADT Binary Tree part of who.docxrochellwa9f
Write a program in Java to implement the ADT Binary Tree part of whose definition is given below. You are also to write a driver program that demonstrates the correctness of your implementation by way of taking a series of commands from a text file and carrying them out. In each binary tree that you will deal with, the values are distinct (i.e. there are no duplicates).
Note: Code for binary tree that I discussed in class is available on Isidore. Feel free to use it but you will assume responsibility for the correctness.
The ADT Binary Tree
The only (private) data member you can use is root, as given below. However, feel free to use as many private member functions as you need.
/* Class BinaryTree */
public class BinaryTree> {
/* Class BinaryNode */
static private class BinaryNode> {
T
BinaryNode
BinaryNode
element; // data part
left; // left child
right; // right child
// Add appropriate constructors for BinaryNode
} // end of BinaryNode
private BinaryNode root; // root of the tree
private final int LCHILD = 1; // constant for left child
private final int RCHILD = 2; // constant for right child
// constructor for BinaryTree
public BinaryTree() {
root = null; // construct an empty tree
}
// Below are the methods that you must implement
//
// Create a tree with the given item as the root with its
// subtrees being empty.
// Post: Previous value of the tree is lost.
//
public void insertRoot (T item)
// If node containing parent exists, and if the specified // child is absent, create the specified child of parent // with item as data element and return true; otherwise
// return false.
//
// Pre: data items in the tree are distinct, i.e., no
duplicates.
// item, if it can be successfully inserted, is
different from
// each value in the tree.
// Post: if insertion were successful, item is the specified
child of
// parent.
// Parameters:
// item: data item to be inserted
// parent: data item of the potential parent // child == 1 => item is to be inserted as left
child of parent
// child == 2 => item is to be inserted as right
child of parent
// Return Value:
// true, if insertion succeeded, and false
otherwise.
public boolean insertItem (T item, T parent, int child)
// Print the tree contents in inorder to the stream
// associated with the printwriter output
public void printTree(PrintWriter output)
// Returns true if val1 exists, val2 exists, and they are
// siblings; otherwise, returns false
public boolean siblings (T val1, T val2)
// print to the given printwriter the frontier of the tree, // i.e., all the leaves in a "right to left reading of the // leaves” order; consecutive items are separated by a space public void printFrontier (PrintWriter output)
// delete subtree rooted at item, if item is present;
// otherwise, tree remains unchanged
public void deleteSubtree (T item)
// Post: if item is present, returns refer.
Please write in C++ and should be able to compile and debug.Thank yo.pdfajaycosmeticslg
Please write in C++ and should be able to compile and debug.Thank you
Create a class called BinaryTreeDeque. This binary tree implements all of the functionality of
the BinaryTree class, but instead of storing its values in a tree structure, the element values are
stored in a deque, using pointers to maintain the relationship between the binary tree and its node
values. Additionally: deque * getValues() - returns a copy of the deque the current array of
values (which should be in insertion order).
Solution
Following are steps to insert a new node in Complete Binary Tree.
1. If the tree is empty, initialize the root with new node.
2. Else, get the front node of the queue.
…….If the left child of this front node doesn’t exist, set the left child as the new node.
…….else if the right child of this front node doesn’t exist, set the right child as the new node.
3. If the front node has both the left child and right child, Dequeue() it.
4. Enqueue() the new node.
Code :-
-------------------------
binarytreedequeue.h
#ifndef BINARYTREEDEQUE_H
#define BINARYTREEDEQUE_H
// Program for linked implementation of complete binary tree
#include
#include
// For Queue Size
#define SIZE 50
// A tree node
struct node
{
int data;
struct node *right,*left;
};
// A queue node
struct Queue
{
int front, rear;
int size;
struct node* *array;
};
class BinaryTreeDeque
{
public:
BinaryTreeDeque();
struct node* newNode(int data);
struct Queue* createQueue(int size);
int isEmpty(struct Queue* queue);
int isFull(struct Queue* queue);
int hasOnlyOneItem(struct Queue* queue);
void Enqueue(struct node *root, struct Queue* queue);
struct node* Dequeue(struct Queue* queue);
struct node* getFront(struct Queue* queue);
int hasBothChild(struct node* temp);
void insert(struct node **root, int data, struct Queue* queue);
void display(struct Queue* queue);
node * getValues(struct Queue* queue);
};
#endif // BINARYTREEDEQUE_H
binarydequeue.cpp
---------------------------------------
#include \"binarytreedeque.h\"
BinaryTreeDeque::BinaryTreeDeque()
{
}
// A utility function to create a new tree node
struct node* BinaryTreeDeque::newNode(int data)
{
struct node* temp = (struct node*) malloc(sizeof( struct node ));
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
// A utility function to create a new Queue
struct Queue* BinaryTreeDeque::createQueue(int size)
{
struct Queue* queue = (struct Queue*) malloc(sizeof( struct Queue ));
queue->front = queue->rear = -1;
queue->size = size;
queue->array = (struct node**) malloc(queue->size * sizeof( struct node* ));
int i;
for (i = 0; i < size; ++i)
queue->array[i] = NULL;
return queue;
}
// Standard Queue Functions
int BinaryTreeDeque::isEmpty(struct Queue* queue)
{
return queue->front == -1;
}
int BinaryTreeDeque::isFull(struct Queue* queue)
{ return queue->rear == queue->size - 1; }
int BinaryTreeDeque::hasOnlyOneItem(struct Queue* queue)
{ return queue->front == queue->rear; }
void BinaryTreeDeque::Enqueue(struct node *root, s.
Given a newly created Binary Search Tree with the following numerica.pdfhadpadrrajeshh
Given a newly created Binary Search Tree with the following numerical key input sequence
(from left to right): 9, 4, 12, 7, 5, 2, 20, 14, 11, 13, 19, 16, 17, 42, 24
a.) We are asked to add a function Position lowestKey(const Position& v) const to the class
SearchTree.
Function prototype: Position lowestKey(const Position& v);
input argument: position of the starting node in the binary search tree to calculate from. For the
whole tree this would be the position for the root of the tree.
return value: position of the node having the lowest key value.
i. Describe strategy with reasonings and examples to convince that it will work.
ii. Implement the function using C++ and show the source code listing.
b) We are also asked to add a function Position highestKey(const Position& v) const to the class
SearchTree.
Function prototype: Position highestKey(const Position& v) const;
input argument: position of the node in the binary search tree to calculate from. For the whole
tree this would be the position for the root of the tree.
return value: position of the node having the highest key value.
i. Describe strategy with reasonings and examples to convince that it will work.
ii. Implement the function using C++ and show the source code listing.
Solution
#include
#include
/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct node
{
int data;
struct node* left;
struct node* right;
};
/* Helper function that allocates a new node
with the given data and NULL left and right
pointers. */
struct node* newNode(int data)
{
struct node* node = (struct node*)
malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
}
/* Give a binary search tree and a number,
inserts a new node with the given number in
the correct place in the tree. Returns the new
root pointer which the caller should then use
(the standard trick to avoid using reference
parameters). */
struct node* insert(struct node* node, int data)
{
/* 1. If the tree is empty, return a new,
single node */
if (node == NULL)
return(newNode(data));
else
{
/* 2. Otherwise, recur down the tree */
if (data <= node->data)
node->left = insert(node->left, data);
else
node->right = insert(node->right, data);
/* return the (unchanged) node pointer */
return node;
}
}
/* Given a non-empty binary search tree,
return the minimum data value found in that
tree. Note that the entire tree does not need
to be searched. */
int minValue(struct node* node) {
struct node* current = node;
/* loop down to find the leftmost leaf */
while (current->left != NULL) {
current = current->left;
}
return(current->data);
}
/* Driver program to test sameTree function*/
int main()
{
struct node* root = NULL;
root = insert(root, 4);
insert(root, 2);
insert(root, 1);
insert(root, 3);
insert(root, 6);
insert(root, 5);
printf(\"\ Minimum value in BST is %d\", minValue(root));
getchar();
return 0;
}
#include
#include
/* A binary tree node has data, pointer to left child
.
C programming. Answer question only in C code Ninth Deletion with B.pdfinfo309708
C programming. Answer question only in C code Ninth: Deletion with Binary Search Tree (20
points) In the ninth part, you will extend the binary search tree in the eighth part to support the
deletion of a node. The deletion of a node is slightly trickier compared to the search and insert in
the eighth The deletion is straightforward if the node to be deleted has only one child. You make
the parent of the node to be deleted point to that child. In this scenario, special attention must be
paid only when the node to be deleted is the root Deleting a node with two children requires
some more work. In this case, you must find the minimum element in the right subtree of the
node to be deleted. Then you insert that node in the place where the node to be deleted was. This
process needs to be repeated to delete the minimum node that was just moved In either case, if
the node to be deleted is the root, you must update the pointer to the root to point to the new root
node Input format: This program takes a file name as argument from the command line. The file
is either blank or contains successive lines of input. Each line contains a character, \'i or \'d\'
followed by a tab and an integer. For each line that starts with \'i\', your program should insert
that number in the binary search tree if it is not already there. If the line starts with a \'s, your
program should search for that value. If the line starts with a \'d\', your program should delete
that value from the tree output format: For each line in the input file, your program should print
the status/result of the operation. For insert and search, the output is the same as in the Eighth
Part: For an insert operation, the program should print either \"inserted\" with a single space
followed by a number the height of the inserted mode in the tree, or \"duplicate\" if the value is
already present in the tree. The height of the root node is 1. For a search, the program should
either print \"present\" followed by the height of the node, or absent\" based on the outcome of
the search. For a delete, the program should print \"success or \"fail\" based on the whether the
value was present or not. Again, as in the Eight Part, your program should print \"error\" (and
nothing else) if the file does not exist or for input lines with improper structure Example
Execution: Lets assume we have a file filel.txt with the following contents: i 5 i 3 i 4 i 1 i 6 i 2 s
1 d 3 s 2 Executing the program in the following fashion should produce the output shown
below:
Solution
// C program to demonstrate delete operation in binary search tree
#include
#include
struct node
{
int key;
struct node *left, *right;
};
// A utility function to create a new BST node
struct node *newNode(int item)
{
struct node *temp = (struct node *)malloc(sizeof(struct node));
temp->key = item;
temp->left = temp->right = NULL;
return temp;
}
// A utility function to do inorder traversal of BST
void inorder(struct node *root)
{
if (root != NULL)
.
Required to augment the authors Binary Search Tree (BST) code to .docxdebishakespeare
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 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 the ...
Help in JAVAThis program should input numerator and denominator f.pdfmanjan6
Help in JAVA:
This program should input numerator and denominator from a file, create a Fraction object
(reducing the fraction if necessary) and then save the fraction to an ArrayList. This list will then
be sorted, and output.
Make one method to input, create, and add to the ArrayList. Another method call to sort. And the
third method to output the contents of the (sorted) ArrayList.
The input file will consist of an (unknown) quantity of ints representing numerator denominator
pairs, which may be negative or zero.
You will need to think about your constructor - you will find it easier if you follow these rules
1. If both numerator and denominator are negative make them both positive
2. if the numerator is positive but the denominator is negative switch both so that the numerator
is negative and the denominator positive
3. any other case leave as is.
what I have so far:
public static class Fraction {
private int numerator;
private int denominator;
public Fraction() {
numerator = 0;
denominator = 1;
}
public Fraction(int n, int d) {
int g = gcd(n, d);
numerator = n/g;
denominator = d/g;
}
public int getNumerator() {
return numerator;
}
public void setNumerator(int n) {
int d = denominator;
int g = gcd(n, d);
numerator = n / g;
denominator= d/g;
}
public int getDenominator() {
return denominator;
}
public void setDenominator(int d) {
int n = numerator;
int g = gcd(n, d);
denominator = d / g;
numerator= n/g;
}
public Fraction add(Fraction g) {
int a = this.numerator;
int b = this.denominator;
int c = g.numerator;
int d = g.denominator;
Fraction v = new Fraction(a * d + b * c, b * d);
return v;
}
public Fraction subtract(Fraction g) {
int a = this.numerator;
int b = this.denominator;
int c = g.numerator;
int d = g.denominator;
Fraction v = new Fraction(a * d - b * c, b * d);
return v;
}
public Fraction multiply(Fraction g) {
int a = this.numerator;
int b = this.denominator;
int c = g.numerator;
int d = g.denominator;
Fraction v = new Fraction(a * c, b * d);
return v;
}
public Fraction divide(Fraction g) {
int a = this.numerator;
int b = this.denominator;
int c = g.numerator;
int d = g.denominator;
Fraction v = new Fraction(a * d, b * c);
return v;
}
public String toString() {
return numerator + \"/\" + denominator;
}
private int gcd(int int1, int int2) {
int i = 0;
int smallest=0;
if (int2>0){
if (int1 < int2) {
smallest=int1;
}
else{
smallest= int2;
}
for (i = smallest; i > 0; i--) {
if ((int1 % i == 0) && (int2 % i == 0)) {
break;
}
}
}
return i;
}
public int input(){
File inFile = new File(\"h7.txt\");
Scanner fileInput = null;
try {
fileInput = new Scanner(inFile);
} catch (FileNotFoundException ex) {
}
fileInput.nextInt();
}
public int sort(int input){
Collections.sort();
}
public int output(){
System.out.println();
}
}
public static void main(String[] args) {
}
}
Solution
Fraction class is used to represents fractions. It is always used to reduced to lowest terms.If
fraction is negative then the numerator will always be negative and all op.
Modify this code to do an Insert function for an AVL tree, instead o.pdffathimaoptical
Match the cost behavior that is described with the proper cost type. The unit cost of an item is
$30 per unit when activity is 10,000 units and $15 per unit when activity is 20,000 units. The
total cost of an item is $30,000 when activity is 10,000 units and $30,000 when activity is 20,000
units. The total cost of an item is $30,000 when activity is 10,000 units and $50,000 when
activity is 20,000 units. 1. Variable cost 2. Fixed Cost The unit cost of an item is $30 per unit
when activity is 10,000 units and $20 per unit when activity is 20,000 units 3. Mixed Cost The
total cost of an item is $30,000 when activity is 10,000 units and $60,000 when activity is 20,000
units. The unit cost of an item is $30 per unit when activity is 10,000 units and $30 per unit when
activity is 20,000 units.
Solution
Variable cost is constant or same in per unit but varies in total with change in output
Fixed cost is constant in total but varies in per unit [ that is doesnot change with change in
output]
Mixed cost is neither constant in total nor in per unit
A)Fixed cost ,since same in total [10000*30 = 300000 or 15*20000 = 300000]
B)Fixed cost ,since same in total
C)Mixed cost,neither constant in per unit nor in total
D)Mixed cost ,neither constant in per unit nor in total
E)Variable cost ,constant in per unit [30000/10000 or 60000/20000 = $ 3 per unit]
F)Variable cost .
c).
1 COMP 182 Fall 2016 Project 6 Binary Search Trees .docxaryan532920
1
COMP 182 Fall 2016
Project 6 Binary Search Trees
You will implement a container for integer values using a Binary Search Tree for the underlying data
structure. The operations or features that your container will support are
Data Management
insert (or add or put)
delete (or remove)
find (or lookup or get)
traversal (or show)
I/O
generate (random number generation)
array input/output (conversion from/to array)
file input/output (read/write)
menu (for command-line interaction with user)
interface IBST {
public void insert(int v);
public boolean delete(int v);
public boolean find(int v);
}
class Node {
public int data;
public Node left, right;
// other methods if you want …
}
class MyTree implements IBST {
private Node root;
public MyTree() { … }
public MyTree(int[] x) { … }
public void insert(int value) { … }
public boolean delete(int value) { … }
public boolean find(int value) { … }
public int getHeight(boolean output) { … }
public boolean confirm() { … }
public String toString() { … }
public String toString(String type) { … }
public void show() { … }
public void show(String type) { … }
private String inOrder() { … }
private String preOrder() { … }
private String postOrder() { … }
public void menu() { … }
}
2
Menu
Write the menu method to support the following options:
generate 20 1000 // fills tree with random numbers
insert 37 // inserts value
delete 23 // tries to delete, prints “okay” or “not found”
find 92 // tries to find, prints “found” or “not found”
show // by default, shows inorder traversal
show inorder // shows inorder traversal
show preorder // shows preorder traversal
show postorder // shows postorder traversal
confirm // confirms that tree satisfies the BST property (for testing)
// also prints performance info: # nodes, log2(# nodes), height
Performance Measures for BST
The performance of the BST depends on how “flat” and short the tree becomes due to insertions and
deletions. A flat short tree can be searched quickly, a tail skinny tree takes longer. Equivalently, we could
say that performance depends on how balanced or unbalanced the tree is. A flat short tree is relatively
balanced, a tall skinny tree is relatively unbalanced. We can get a good estimate how balanced a tree is at
any time by observing or measuring three values:
Total Number of Nodes in the BST
Average Number of Nodes on Any Path from Root to Leaf
Height (Maximum Number of Nodes on Any Path from Root to Leaf)
In the best case, the height will equal log2(# nodes), and the typical operation will have complexity O(log
n). In the worst case, the height equals the number of nodes, and the typical operation will have complexity
O(n). In the worst case, the performance of the BST is the same as the performance of the linked list.
Recursi ...
Consider this code using the ArrayBag of Section 5.2 and the Locat.docxmaxinesmith73660
Consider this code using the ArrayBag of Section 5.2 and the Location class from Chapter 2. What is the output?
Location i = new Location(0, 3);
Location j = new Location(0, 3);
b.add(i);
b.add(j);
System.out.println(b.countOccurrences(i));
A. 0
B. 1
C. 2
D. 3
Suppose that b and c are Integer objects. A typical use of the clone method looks like this:
b = (Integer) c.clone( );
Write a short clear explanation of why the (Integer) type cast is required in this typical example.
A. obj = s;
B. s = obj;
C. s = (String) obj;
D. Two or more answers are correct.
Suppose that obj is an Object variable and s is a String variable. Which of the following statements
is a correctly-compiling widening conversion? Don't worry about possible run-time exceptions
A. obj = s;
B. s = obj;
C. s = (String) obj;
D. Two or more answers are correct.
Suppose that x and y are reference variables and a program activates x.equals(y). What occurs if x is the null reference?
A. A NullPointerException occurs
B. It always returns true.
C. It always returns false.
D. It returns true if y is also a null reference; otherwise it returns false.
Consider the implementation of the Stack using a partially-filled array.
What goes wrong if we try to store the top of the Stack at location [0] and the bottom of the Stack at the last used position of the array?
A. Both peek and pop would require linear time.
B. Both push and pop would require linear time.
C. The Stack could not be used to check balanced parentheses.
D. The Stack could not be used to evaluate postfix expressions.
Write some lines of code that declares an Integer object, using the Integer wrapper class.
Assign the value 42 to this object, then copy this value from the Integer object to an ordinary int variable.
Consider the usual algorithm for determining whether a sequence of parentheses is balanced.
What is the maximum number of parentheses that will appear on the stack AT ANY ONE TIME when the algorithm analyzes: (()(())(()))?
A. 1
B. 2
C. 3
D. 4
E. 5 or more
Consider the usual algorithm to convert an infix expression to a postfix expression.
Suppose that you have read 10 input characters during a conversion and that the
stack now contains the symbols as shown below. Suppose that you read and process
the 11th symbol of the input. What symbol is at the top of the stack in the case where
the 11th symbol is each of the choices shown?
Which of the following stack operations could result in stack underflow?
Answer
A. is_empty
B. pop
C. push
D. Two or more of the above answers
What is the value of the postfix expression 6 3 2 4 + - *:
Answer
A. Something between -15 and -100
B. Something between -5 and -15
C. Something between 5 and -5
D. Something between 5 and 15
E. Something between 15 and 100
1. An array o.
C++ (pronounced "see plus plus") is a computer programming language based on C. It was created for writing programs for many different purposes. In the 1990s, C++ became one of the most used programming languages in the world.
The C++ programming language was developed by Bjarne Stroustrup at Bell Labs in the 1980s, and was originally named "C with classes". The language was planned as an improvement on the C programming language, adding features based on object-oriented programming. Step by step, a lot of advanced features were added to the language, like operator overloading, exception handling and templates.
Help please!!(Include your modified DList.java source code file in.pdfjyothimuppasani1
Help please!!
(Include your modified DList.java source code file in your homework solution zip archive)
Using
whatever Java IDE you prefer, create a project and add DList.java and DListTest.java to it (these
files are provided
in the Week 6 Source zip archive). Modify DList to implement a method that removes all
occurrences of a specific
integer from the list. Here is the pseudocode:
Method removeAll(In: Integer pData) Returns Nothing
Define index variable i and initialize i to 0
While i < the size of this Dlist Do
If get(i) equals pData Then
remove(i)
Else
Increment i
End If
End While
End Method removeAll
Next, modify DListTest() to add test case 21 which tests that removeAll() works correctly.
WHat more do i need to provide to get help on this???
Solution
/* DListNode.java */
/**
* A DListNode is a node in a DList (doubly-linked list).
*/
class DListNode {
/**
* item references the item stored in the current node.
* prev references the previous node in the DList.
* next references the next node in the DList.
*
* DO NOT CHANGE THE FOLLOWING FIELD DECLARATIONS.
*/
public Object item;
protected DListNode prev;
protected DListNode next;
/**
* DListNode() constructor.
* @param i the item to store in the node.
* @param p the node previous to this node.
* @param n the node following this node.
*/
DListNode(Object i, DListNode p, DListNode n) {
item = i;
prev = p;
next = n;
}
}
/* DList.java */
/**
* A DList is a mutable doubly-linked list ADT. Its implementation is
* circularly-linked and employs a sentinel (dummy) node at the head
* of the list.
*
* DO NOT CHANGE ANY METHOD PROTOTYPES IN THIS FILE.
*/
class DList {
/**
* head references the sentinel node.
* size is the number of items in the list. (The sentinel node does not
* store an item.)
*
* DO NOT CHANGE THE FOLLOWING FIELD DECLARATIONS.
*/
protected DListNode head;
protected int size;
/* DList invariants:
* 1) head != null.
* 2) For any DListNode x in a DList, x.next != null.
* 3) For any DListNode x in a DList, x.prev != null.
* 4) For any DListNode x in a DList, if x.next == y, then y.prev == x.
* 5) For any DListNode x in a DList, if x.prev == y, then y.next == x.
* 6) size is the number of DListNodes, NOT COUNTING the sentinel,
* that can be accessed from the sentinel (head) by a sequence of
* \"next\" references.
*/
/**
* newNode() calls the DListNode constructor. Use this class to allocate
* new DListNodes rather than calling the DListNode constructor directly.
* That way, only this method needs to be overridden if a subclass of DList
* wants to use a different kind of node.
* @param item the item to store in the node.
* @param prev the node previous to this node.
* @param next the node following this node.
*/
protected DListNode newNode(Object item, DListNode prev, DListNode next) {
return new DListNode(item, prev, next);
}
/**
* DList() constructor for an empty DList.
*/
public DList() {
// Your solution here.
head = newNode(null, head, head);
head.prev = head;
head.next = head;
si.
20-13 Programming Project #05A Given the IntNode class- define the Fin.docxDavidxyNSimpsons
20.13 Programming Project #05A
Given the IntNode class, define the FindMax() function to return the largest value in the list or -99 if the list is empty. Assume all values in the list are non-negative.
Ex: If the list contains:
FindMax(headNode) returns 191.
Ex: If the list contains:
FindMax(headNode) returns -99.
**Please make sure returns -99 and not -1**
Given code:
main.cpp
#include <iostream>
using namespace std;
class IntNode {
public:
// Constructor
IntNode(int dataInit);
// Get node value
int GetNodeData();
// Get pointer to next node
IntNode* GetNext();
/* Insert node after this node.
Before: this -- next
After: this -- node -- next
*/
void InsertAfter(IntNode* newNode);
private:
int dataVal;
IntNode* nextNodePtr;
};
// Constructor
IntNode::IntNode(int dataInit) {
this->dataVal = dataInit;
nextNodePtr = nullptr;
}
// Get node value
int IntNode::GetNodeData() {
return this->dataVal;
}
// Get pointer to next node
IntNode* IntNode::GetNext() {
return this->nextNodePtr;
}
/* Insert node after this node.
Before: this -- next
After: this -- node -- next
*/
void IntNode::InsertAfter(IntNode* newNode) {
IntNode* tempNext = this->nextNodePtr;
this->nextNodePtr = newNode;
newNode->nextNodePtr = tempNext;
}
// Return largest value in the list
int FindMax(IntNode* headNode) {
/* Type your code here. */
}
int main() {
IntNode* headNode = new IntNode(-1);
IntNode* currNode;
IntNode* lastNode;
int max;
// Initiaize head node
lastNode = headNode;
// Add nodes to the list
for (int i = 0; i < 20; ++i) {
currNode = new IntNode(i);
lastNode->InsertAfter(currNode);
lastNode = currNode;
}
max = FindMax(headNode);
cout << "Max is " << max;
return 0;
}
.
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
}
/* ...
This is problem is same problem which i submitted on 22017, I just.pdffcaindore
There is a host of sociological and cultural research that paints a robust picture of the effects of
globalization on culture. This Application focuses on the flows of culture between Western and
developing nations. As a practitioner in this global environment, you should be familiar with
these culture effects. Use newspapers, magazines, and the Internet to research cultural changes in
both Western and developing countries due to globalization. Then perform the following tasks:
Outline the cultural aspects of globalization. Take an anthropological, rather than a business,
perspective. Explain how you think understanding culture helps in doing business in today\'s
global economy. Cite resources to justify your response.
Solution
Information technology has penetrated almost every aspect of our lives, “shrinking” our world
into a global village.
Economies and cultures have come closer. People are now aware of the cultures, traditions,
lifestyle, living conditions
prevailing in almost every corner of the world. Interestingly, this is going beyond awareness and
into a state of
integration that is a result of cross-pollinated views, ideologies, products and services.
This evolution is termed as “globalization.”
Culture has many definitions. My own definition is that culture is our collective experience as a
society,
and its impact on our reaction and decision-making relative to every-day facts and
circumstances.
Why is cross-cultural competence critical to your professional future and the viability of your
company?
It’s omnipresent in every business interaction and strategic decision.It is not feasible to be an
expert on
all the world’s cultures. It is possible, however, to incorporate a cross-cultural framework that
improves
cross-cultural understanding and interactions.
Multinational firms whose operations are borderless have to consider the cultural variability of
different regions
of the world and develop cultural understanding. Major cultural constraints encountered by
businesses include local
attitudes, taste preferences, language, religion, management style, gender discrimination, skills,
personalities,
education, etc. To be successful, they need to mold their business actions in accordance with the
local cultural models,
they need to establish a global mindset.
Let’s consider an example of the food giant, McDonald’s. The company enjoys a global
presence; operating in more than
100 countries serving 70 million people every day. Their headquarters and senior management
are U.S.-based but they
entrust their local operations to local managers of the countries they operate in. Operations in
more than 50 percent of
their outlets are franchised. Furthermore, their menus are customized according to cultural
habits and local taste
preferences in every country. It is without a doubt that global thinking and cultural
understanding are both powerful
business tools which allow multinational firms to dominate the local markets and establish a
global pres.
Need Help with this Java Assignment. Program should be done in JAVA .pdfarchiesgallery
Need Help with this Java Assignment. Program should be done in JAVA please
Complete required scripts based on eclipse and troubleshoot the scripts until the tasks are done.
1. Implement a binary search tree (write the code for it), for a height of 2 or higher. Please show
the output if you can Thank you in advance!
Solution
I have compiled this code and checked for errors, worked fine.
Also after the code I have pasted the Output transcript to show what User Inputs I gave and what
all outputs I got.
// Java Program to Implement Binary Tree
import java.util.Scanner;
/* Define Class BinaryTreeNode */
class BinaryTreeNode
{
BinaryTreeNode left, right;
int data;
/* Constructor */
public BinaryTreeNode()
{
left = null;
right = null;
data = 0;
}
/* Constructor */
public BinaryTreeNode(int n)
{
left = null;
right = null;
data = n;
}
/* Function to set left node */
public void setLeft(BinaryTreeNode n)
{
left = n;
}
/* Function to set right node */
public void setRight(BinaryTreeNode n)
{
right = n;
}
/* Function to get left node */
public BinaryTreeNode getLeft()
{
return left;
}
/* Function to get right node */
public BinaryTreeNode getRight()
{
return right;
}
/* Function to set data to node */
public void setData(int d)
{
data = d;
}
/* Function to get data from node */
public int getData()
{
return data;
}
}
/* Define anothe Class Operations to perform required operationns on Binary Tree*/
class Operations
{
private BinaryTreeNode root;
/* Constructor */
public Operations()
{
root = null;
}
/* Function to check if tree is empty */
public boolean isEmpty()
{
return root == null;
}
/* Functions to insert data */
public void insert(int data)
{
root = insert(root, data);
}
/* Function to insert data recursively */
private BinaryTreeNode insert(BinaryTreeNode node, int data)
{
if (node == null)
node = new BinaryTreeNode(data);
else
{
if (node.getRight() == null)
node.right = insert(node.right, data);
else
node.left = insert(node.left, data);
}
return node;
}
/* Function to count number of nodes */
public int countNodes()
{
return countNodes(root);
}
/* Function to count number of nodes recursively */
private int countNodes(BinaryTreeNode r)
{
if (r == null)
return 0;
else
{
int l = 1;
l += countNodes(r.getLeft());
l += countNodes(r.getRight());
return l;
}
}
/* Function to search for an element */
public boolean search(int val)
{
return search(root, val);
}
/* Function to search for an element recursively */
private boolean search(BinaryTreeNode r, int val)
{
if (r.getData() == val)
return true;
if (r.getLeft() != null)
if (search(r.getLeft(), val))
return true;
if (r.getRight() != null)
if (search(r.getRight(), val))
return true;
return false;
}
/* Function for inorder traversal */
public void inorder()
{
inorder(root);
}
private void inorder(BinaryTreeNode r)
{
if (r != null)
{
inorder(r.getLeft());
System.out.print(r.getData() +\" \");
inorder(r.getRight());
}
}
/* Function for preorder traversal */
public void preorder()
{
preorder(root);
}
priva.
Please i need help on following program using C++ Language.Add the.pdfezzi552
Instructions write a c program to solve the following problem. Upload your source code file to
Canvas. The file name must be of the form hwloop your name.c Substitute your first and last
name for \"your name\" in the file name. Example: Student\'s name is Sparky Watts. The file
name is hwloop sparky watts.c Problem Statement create a program that calculates twelve
month\'s interest and principle loan balance. Your program will ask the user for the starting
principle balance, annual interest rate, and monthly payment amount. Your program will verify
the input is reasonable, as described in the Error checking section below. After obtaining
reasonable the program will process 12 months of payments. The will show the accrued interest
and updated loan balance after each month\'s payment. The total interest paid and total payment
amounts for the 12 month period will also be calculated and displayed. Your program output
should resemble the output below. AUsers williidialDesktoplhw04MbinlDebuglhw04.exe Enter
loan anount: 32000.00 Enter annual interest rate 7.99 Enter monthly payment 752.84
Solution
#include
#include
int main()
{
double loan_amount = 0;
printf(\"Enter loan amount :\");
if (scanf(\"%lf\", &loan_amount) != 1)
{
printf(\"Please enter loan amount correctly\ \");
return -1;
}
if (loan_amount < 500)
{
printf(\"Loan amount should be greater than 500\ \");
return 1;
}
if (loan_amount > 100000)
{
printf(\"Loan amount should be less than 100000\ \");
return -1;
}
printf(\"Enter annual interest rate: \");
double interest_rate;
if (scanf(\"%lf\", &interest_rate) != 1)
{
printf(\"Please enter interest rate correctly\ \");
return -1;
}
if (interest_rate < 0 || interest_rate > 8.99)
{
printf(\"Interest rate should be in range of 0 to 8.99\ \");
return -1;
}
double monthly_payments;
printf(\"Enter monthly payment: \");
if (scanf(\"%lf\", &monthly_payments) != 1)
{
printf(\"Please monthly payment correctly\ \");
return -1;
}
double first_month_interest = (loan_amount * interest_rate)/(12*100);
if (monthly_payments < first_month_interest)
{
printf(\"Monthly payment should be greater than %f\ \", first_month_interest);
return -1;
}
double total_interest = 0;
double total_paid = 0;
printf(\"\ \");
printf(\"Begin \\t\\t\\t\\tMonthly\\tEnd\ \");
printf(\"Loan\\t\\tAccured\\t\\tPayment\\tLoan\ \");
printf(\"Balance\\t\\tInterest\\tAmount\\tBalance\ \");
printf(\"\ \");
int i;
for(i = 0; i <= 12; i++)
{
printf(\"%0.2f\\t\", loan_amount);
double interest = (loan_amount*interest_rate)/(1200);
printf(\"%0.2f\\t\\t\", interest);
printf(\"%0.2f\\t\", monthly_payments);
loan_amount = loan_amount + interest;
if (loan_amount < monthly_payments)
{
total_paid -= loan_amount;
loan_amount = 0;
printf(\"%0.2f\ \", loan_amount);
break;
}
else
{
loan_amount -= monthly_payments;
total_paid += monthly_payments;
}
printf(\"%0.2f\ \", loan_amount);
total_interest += interest;
}
printf(\"\ \");
printf(\"Annual total\\t%.2f\\t\\t%.2f\ \", total_interest, total_paid);
return 0;
}.
Assignment is Page 349-350 #4 and #5 Use the Linked Lis.pdfformicreation
Assignment is :
\"Page 349-350 #4 and #5 Use the \"Linked List lab\" you have been working on in class and add
the two functions the questions are asking you to develop: divideMid and divideAt. Be sure to
include comments Use meaningful identifier names (constants where appropriate) Do not work
together; no two people should have identical work!?!? Turn in .cpp file AND Turn in a \"print-
screen\' of your output (press \"print-screen\' on keyboard, then \'paste\' in MS-Word)\"
How do you solve QUESTION #5 in the book data structures using c++ by D.S. Malik in Visiual
Studios using the linked list below with what is being asked? Please need help
Linked list :
#include
#include
using namespace std;
struct nodeType
{
int info;
nodeType *link;
};
void createList(nodeType*& first, nodeType*& last);
void printList(nodeType*& first);
void insertFront(nodeType*& first);
void insertBack(nodeType*& last);
void deleteFirst(nodeType*& first);
void deleteLast(nodeType*& last, nodeType* first);
int main()
{
nodeType *first, *last;
int num;
createList(first, last);
int choice;
while(true)
{
cout<<\"1. Insert Front.\ 2. Insert Last.\ 3. Delete Front.\ 4. Delete Last.\ 5. Print List.\ 6. Exit.\
\";
cout<<\"Enter your choice: \";
cin>>choice;
switch(choice)
{
case 1: insertFront(first); break;
case 2: insertBack(last); break;
case 3: deleteFirst(first); break;
case 4: deleteLast(last, first); break;
case 5: printList(first); break;
case 6: return 0;
default: cout<<\"Invalid menu option. Try again.\"<>number;
while (number != -999)
{
newNode = new nodeType; // create new node
newNode->info = number;
newNode->link = NULL;
if (first == NULL)
{
first = newNode;
last = newNode;
}
else
{
last->link = newNode;
last = newNode;
}
cout<<\"Enter an integer (-999 to stop): \";
cin>>number;
} // end of while-loop
} // end of build list function
void deleteFirst(nodeType*& first)
{
nodeType *temp;
temp= first;
first= temp->link;
delete temp;
return;
}
void deleteLast(nodeType*& last, nodeType* current)
{
nodeType *temp;
while(current->link != NULL)
{
temp=current;
current=current->link;
}
temp=last;
current->link=NULL;
delete temp;
last = current;
return;
}
void insertFront(nodeType*& front)
{
int num;
cout<<\"\ Enter the number to insert: \";
cin>>num;
nodeType *newNode = new nodeType;
newNode->info=num;
newNode->link= front;
front= newNode;
return;
}
void insertBack(nodeType*& last)
{
int num;
cout<<\"\ Enter the number to insert: \";
cin>>num;
nodeType *newNode = new nodeType;
newNode->info=num;
newNode->link= NULL;
last->link= newNode;
last = newNode;
return;
}
void printList(nodeType*& first)
{
cout<<\"Inside printList...printing linked list...\ \"<info << \" \";
current = current->link;
}
cout<
#include
using namespace std;
struct nodeType
{
int info;
nodeType *link;
};
void createList(nodeType*& first, nodeType*& last);
void printList(nodeType*& first);
void insertFront(nodeType*& first);
void insertBack(nodeType*& last);
void deleteFirst(nodeType*& first);
void dele.
Learning ResourcesRequired ReadingsToseland, R. W., & Ri.docxfestockton
Learning Resources
Required Readings
Toseland, R. W., & Rivas, R. F. (2017).
An introduction to group work practice
(8th ed.). Boston, MA: Pearson.
Chapter 11, “Task Groups: Foundation Methods” (pp. 336-363)
Chapter 12, “Task Groups: Specialized Methods” (pp. 364–395)
Van Velsor, P. (2009). Task groups in the school setting: Promoting children’s social and emotional learning.
Journal for Specialists in Group Work
,
34
(3), 276–292.
Document:
Group Wiki Project Guidelines (PDF)
Recommended Resources
Holosko, M. J., Dulmus, C. N., & Sowers, K. M. (2013). Social work practice with individuals and families: Evidence-informed assessments and interventions. Hoboken, NJ: John Wiley & Sons, Inc.
Chapter 1 “Assessment of Children”
Chapter 2 “Intervention with Children”
Discussion: Task Groups
Group work is a commonly used method within school settings. Because peer interaction is important in the emotional and social development of children, the task group can serve as a wonderful therapeutic setting and tool; however, many factors should be considered when implementing this type of intervention.
For this Discussion, read the Van Velsor (2009) article.
By Day 3
Post
your understanding of task groups as an intervention for children. Use the model for effective problem solving to compare and contrast (how to identify the problem, develop goals, collect data). How does this model differ from a traditional treatment group? What are the advantages and possible disadvantages of this model? Describe how you might use this model for adults. What populations would most benefit from this model?
.
LeamosEscribamos Completa el párrafo con las formas correctas de lo.docxfestockton
Leamos/Escribamos Completa el párrafo con las formas correctas de los verbos en paréntesis. Usa el pretérito o el imperfecto.
Yo __1__ (criarse) en el campo, pero mi familia __2__
(mudarse) a la ciudad cuando yo tenía doce años. Hablábamos
aymara en mi pueblo, y mi mamá no __3__ (expresarse) bien en
español. Mis hermanos y yo __4__ (comunicarse) sin problema
porque habíamos estudiado español en el colegio. Con dificultad
nosotros __5__ (acostumbrarse) al estilo de vida.Yo __6__
(preocuparse) por todo. No me __7__ (gustar) el ruido de los
carros. Pero poco a poco, nostros __8__ (asimilar) el modo de
ser de la gente de la cuidad.Yo __9__ (graduarse) de la
universidad hace poco, mi hermano mayor ahora es arquitecto, y
mi hermano menor __10__ (casarse) el mes pasado.
.
More Related Content
Similar to Assg 12 Binary Search Trees COSC 2336assg-12.cppAssg 12 Binary .docx
Given a newly created Binary Search Tree with the following numerica.pdfhadpadrrajeshh
Given a newly created Binary Search Tree with the following numerical key input sequence
(from left to right): 9, 4, 12, 7, 5, 2, 20, 14, 11, 13, 19, 16, 17, 42, 24
a.) We are asked to add a function Position lowestKey(const Position& v) const to the class
SearchTree.
Function prototype: Position lowestKey(const Position& v);
input argument: position of the starting node in the binary search tree to calculate from. For the
whole tree this would be the position for the root of the tree.
return value: position of the node having the lowest key value.
i. Describe strategy with reasonings and examples to convince that it will work.
ii. Implement the function using C++ and show the source code listing.
b) We are also asked to add a function Position highestKey(const Position& v) const to the class
SearchTree.
Function prototype: Position highestKey(const Position& v) const;
input argument: position of the node in the binary search tree to calculate from. For the whole
tree this would be the position for the root of the tree.
return value: position of the node having the highest key value.
i. Describe strategy with reasonings and examples to convince that it will work.
ii. Implement the function using C++ and show the source code listing.
Solution
#include
#include
/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct node
{
int data;
struct node* left;
struct node* right;
};
/* Helper function that allocates a new node
with the given data and NULL left and right
pointers. */
struct node* newNode(int data)
{
struct node* node = (struct node*)
malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
}
/* Give a binary search tree and a number,
inserts a new node with the given number in
the correct place in the tree. Returns the new
root pointer which the caller should then use
(the standard trick to avoid using reference
parameters). */
struct node* insert(struct node* node, int data)
{
/* 1. If the tree is empty, return a new,
single node */
if (node == NULL)
return(newNode(data));
else
{
/* 2. Otherwise, recur down the tree */
if (data <= node->data)
node->left = insert(node->left, data);
else
node->right = insert(node->right, data);
/* return the (unchanged) node pointer */
return node;
}
}
/* Given a non-empty binary search tree,
return the minimum data value found in that
tree. Note that the entire tree does not need
to be searched. */
int minValue(struct node* node) {
struct node* current = node;
/* loop down to find the leftmost leaf */
while (current->left != NULL) {
current = current->left;
}
return(current->data);
}
/* Driver program to test sameTree function*/
int main()
{
struct node* root = NULL;
root = insert(root, 4);
insert(root, 2);
insert(root, 1);
insert(root, 3);
insert(root, 6);
insert(root, 5);
printf(\"\ Minimum value in BST is %d\", minValue(root));
getchar();
return 0;
}
#include
#include
/* A binary tree node has data, pointer to left child
.
C programming. Answer question only in C code Ninth Deletion with B.pdfinfo309708
C programming. Answer question only in C code Ninth: Deletion with Binary Search Tree (20
points) In the ninth part, you will extend the binary search tree in the eighth part to support the
deletion of a node. The deletion of a node is slightly trickier compared to the search and insert in
the eighth The deletion is straightforward if the node to be deleted has only one child. You make
the parent of the node to be deleted point to that child. In this scenario, special attention must be
paid only when the node to be deleted is the root Deleting a node with two children requires
some more work. In this case, you must find the minimum element in the right subtree of the
node to be deleted. Then you insert that node in the place where the node to be deleted was. This
process needs to be repeated to delete the minimum node that was just moved In either case, if
the node to be deleted is the root, you must update the pointer to the root to point to the new root
node Input format: This program takes a file name as argument from the command line. The file
is either blank or contains successive lines of input. Each line contains a character, \'i or \'d\'
followed by a tab and an integer. For each line that starts with \'i\', your program should insert
that number in the binary search tree if it is not already there. If the line starts with a \'s, your
program should search for that value. If the line starts with a \'d\', your program should delete
that value from the tree output format: For each line in the input file, your program should print
the status/result of the operation. For insert and search, the output is the same as in the Eighth
Part: For an insert operation, the program should print either \"inserted\" with a single space
followed by a number the height of the inserted mode in the tree, or \"duplicate\" if the value is
already present in the tree. The height of the root node is 1. For a search, the program should
either print \"present\" followed by the height of the node, or absent\" based on the outcome of
the search. For a delete, the program should print \"success or \"fail\" based on the whether the
value was present or not. Again, as in the Eight Part, your program should print \"error\" (and
nothing else) if the file does not exist or for input lines with improper structure Example
Execution: Lets assume we have a file filel.txt with the following contents: i 5 i 3 i 4 i 1 i 6 i 2 s
1 d 3 s 2 Executing the program in the following fashion should produce the output shown
below:
Solution
// C program to demonstrate delete operation in binary search tree
#include
#include
struct node
{
int key;
struct node *left, *right;
};
// A utility function to create a new BST node
struct node *newNode(int item)
{
struct node *temp = (struct node *)malloc(sizeof(struct node));
temp->key = item;
temp->left = temp->right = NULL;
return temp;
}
// A utility function to do inorder traversal of BST
void inorder(struct node *root)
{
if (root != NULL)
.
Required to augment the authors Binary Search Tree (BST) code to .docxdebishakespeare
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 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 the ...
Help in JAVAThis program should input numerator and denominator f.pdfmanjan6
Help in JAVA:
This program should input numerator and denominator from a file, create a Fraction object
(reducing the fraction if necessary) and then save the fraction to an ArrayList. This list will then
be sorted, and output.
Make one method to input, create, and add to the ArrayList. Another method call to sort. And the
third method to output the contents of the (sorted) ArrayList.
The input file will consist of an (unknown) quantity of ints representing numerator denominator
pairs, which may be negative or zero.
You will need to think about your constructor - you will find it easier if you follow these rules
1. If both numerator and denominator are negative make them both positive
2. if the numerator is positive but the denominator is negative switch both so that the numerator
is negative and the denominator positive
3. any other case leave as is.
what I have so far:
public static class Fraction {
private int numerator;
private int denominator;
public Fraction() {
numerator = 0;
denominator = 1;
}
public Fraction(int n, int d) {
int g = gcd(n, d);
numerator = n/g;
denominator = d/g;
}
public int getNumerator() {
return numerator;
}
public void setNumerator(int n) {
int d = denominator;
int g = gcd(n, d);
numerator = n / g;
denominator= d/g;
}
public int getDenominator() {
return denominator;
}
public void setDenominator(int d) {
int n = numerator;
int g = gcd(n, d);
denominator = d / g;
numerator= n/g;
}
public Fraction add(Fraction g) {
int a = this.numerator;
int b = this.denominator;
int c = g.numerator;
int d = g.denominator;
Fraction v = new Fraction(a * d + b * c, b * d);
return v;
}
public Fraction subtract(Fraction g) {
int a = this.numerator;
int b = this.denominator;
int c = g.numerator;
int d = g.denominator;
Fraction v = new Fraction(a * d - b * c, b * d);
return v;
}
public Fraction multiply(Fraction g) {
int a = this.numerator;
int b = this.denominator;
int c = g.numerator;
int d = g.denominator;
Fraction v = new Fraction(a * c, b * d);
return v;
}
public Fraction divide(Fraction g) {
int a = this.numerator;
int b = this.denominator;
int c = g.numerator;
int d = g.denominator;
Fraction v = new Fraction(a * d, b * c);
return v;
}
public String toString() {
return numerator + \"/\" + denominator;
}
private int gcd(int int1, int int2) {
int i = 0;
int smallest=0;
if (int2>0){
if (int1 < int2) {
smallest=int1;
}
else{
smallest= int2;
}
for (i = smallest; i > 0; i--) {
if ((int1 % i == 0) && (int2 % i == 0)) {
break;
}
}
}
return i;
}
public int input(){
File inFile = new File(\"h7.txt\");
Scanner fileInput = null;
try {
fileInput = new Scanner(inFile);
} catch (FileNotFoundException ex) {
}
fileInput.nextInt();
}
public int sort(int input){
Collections.sort();
}
public int output(){
System.out.println();
}
}
public static void main(String[] args) {
}
}
Solution
Fraction class is used to represents fractions. It is always used to reduced to lowest terms.If
fraction is negative then the numerator will always be negative and all op.
Modify this code to do an Insert function for an AVL tree, instead o.pdffathimaoptical
Match the cost behavior that is described with the proper cost type. The unit cost of an item is
$30 per unit when activity is 10,000 units and $15 per unit when activity is 20,000 units. The
total cost of an item is $30,000 when activity is 10,000 units and $30,000 when activity is 20,000
units. The total cost of an item is $30,000 when activity is 10,000 units and $50,000 when
activity is 20,000 units. 1. Variable cost 2. Fixed Cost The unit cost of an item is $30 per unit
when activity is 10,000 units and $20 per unit when activity is 20,000 units 3. Mixed Cost The
total cost of an item is $30,000 when activity is 10,000 units and $60,000 when activity is 20,000
units. The unit cost of an item is $30 per unit when activity is 10,000 units and $30 per unit when
activity is 20,000 units.
Solution
Variable cost is constant or same in per unit but varies in total with change in output
Fixed cost is constant in total but varies in per unit [ that is doesnot change with change in
output]
Mixed cost is neither constant in total nor in per unit
A)Fixed cost ,since same in total [10000*30 = 300000 or 15*20000 = 300000]
B)Fixed cost ,since same in total
C)Mixed cost,neither constant in per unit nor in total
D)Mixed cost ,neither constant in per unit nor in total
E)Variable cost ,constant in per unit [30000/10000 or 60000/20000 = $ 3 per unit]
F)Variable cost .
c).
1 COMP 182 Fall 2016 Project 6 Binary Search Trees .docxaryan532920
1
COMP 182 Fall 2016
Project 6 Binary Search Trees
You will implement a container for integer values using a Binary Search Tree for the underlying data
structure. The operations or features that your container will support are
Data Management
insert (or add or put)
delete (or remove)
find (or lookup or get)
traversal (or show)
I/O
generate (random number generation)
array input/output (conversion from/to array)
file input/output (read/write)
menu (for command-line interaction with user)
interface IBST {
public void insert(int v);
public boolean delete(int v);
public boolean find(int v);
}
class Node {
public int data;
public Node left, right;
// other methods if you want …
}
class MyTree implements IBST {
private Node root;
public MyTree() { … }
public MyTree(int[] x) { … }
public void insert(int value) { … }
public boolean delete(int value) { … }
public boolean find(int value) { … }
public int getHeight(boolean output) { … }
public boolean confirm() { … }
public String toString() { … }
public String toString(String type) { … }
public void show() { … }
public void show(String type) { … }
private String inOrder() { … }
private String preOrder() { … }
private String postOrder() { … }
public void menu() { … }
}
2
Menu
Write the menu method to support the following options:
generate 20 1000 // fills tree with random numbers
insert 37 // inserts value
delete 23 // tries to delete, prints “okay” or “not found”
find 92 // tries to find, prints “found” or “not found”
show // by default, shows inorder traversal
show inorder // shows inorder traversal
show preorder // shows preorder traversal
show postorder // shows postorder traversal
confirm // confirms that tree satisfies the BST property (for testing)
// also prints performance info: # nodes, log2(# nodes), height
Performance Measures for BST
The performance of the BST depends on how “flat” and short the tree becomes due to insertions and
deletions. A flat short tree can be searched quickly, a tail skinny tree takes longer. Equivalently, we could
say that performance depends on how balanced or unbalanced the tree is. A flat short tree is relatively
balanced, a tall skinny tree is relatively unbalanced. We can get a good estimate how balanced a tree is at
any time by observing or measuring three values:
Total Number of Nodes in the BST
Average Number of Nodes on Any Path from Root to Leaf
Height (Maximum Number of Nodes on Any Path from Root to Leaf)
In the best case, the height will equal log2(# nodes), and the typical operation will have complexity O(log
n). In the worst case, the height equals the number of nodes, and the typical operation will have complexity
O(n). In the worst case, the performance of the BST is the same as the performance of the linked list.
Recursi ...
Consider this code using the ArrayBag of Section 5.2 and the Locat.docxmaxinesmith73660
Consider this code using the ArrayBag of Section 5.2 and the Location class from Chapter 2. What is the output?
Location i = new Location(0, 3);
Location j = new Location(0, 3);
b.add(i);
b.add(j);
System.out.println(b.countOccurrences(i));
A. 0
B. 1
C. 2
D. 3
Suppose that b and c are Integer objects. A typical use of the clone method looks like this:
b = (Integer) c.clone( );
Write a short clear explanation of why the (Integer) type cast is required in this typical example.
A. obj = s;
B. s = obj;
C. s = (String) obj;
D. Two or more answers are correct.
Suppose that obj is an Object variable and s is a String variable. Which of the following statements
is a correctly-compiling widening conversion? Don't worry about possible run-time exceptions
A. obj = s;
B. s = obj;
C. s = (String) obj;
D. Two or more answers are correct.
Suppose that x and y are reference variables and a program activates x.equals(y). What occurs if x is the null reference?
A. A NullPointerException occurs
B. It always returns true.
C. It always returns false.
D. It returns true if y is also a null reference; otherwise it returns false.
Consider the implementation of the Stack using a partially-filled array.
What goes wrong if we try to store the top of the Stack at location [0] and the bottom of the Stack at the last used position of the array?
A. Both peek and pop would require linear time.
B. Both push and pop would require linear time.
C. The Stack could not be used to check balanced parentheses.
D. The Stack could not be used to evaluate postfix expressions.
Write some lines of code that declares an Integer object, using the Integer wrapper class.
Assign the value 42 to this object, then copy this value from the Integer object to an ordinary int variable.
Consider the usual algorithm for determining whether a sequence of parentheses is balanced.
What is the maximum number of parentheses that will appear on the stack AT ANY ONE TIME when the algorithm analyzes: (()(())(()))?
A. 1
B. 2
C. 3
D. 4
E. 5 or more
Consider the usual algorithm to convert an infix expression to a postfix expression.
Suppose that you have read 10 input characters during a conversion and that the
stack now contains the symbols as shown below. Suppose that you read and process
the 11th symbol of the input. What symbol is at the top of the stack in the case where
the 11th symbol is each of the choices shown?
Which of the following stack operations could result in stack underflow?
Answer
A. is_empty
B. pop
C. push
D. Two or more of the above answers
What is the value of the postfix expression 6 3 2 4 + - *:
Answer
A. Something between -15 and -100
B. Something between -5 and -15
C. Something between 5 and -5
D. Something between 5 and 15
E. Something between 15 and 100
1. An array o.
C++ (pronounced "see plus plus") is a computer programming language based on C. It was created for writing programs for many different purposes. In the 1990s, C++ became one of the most used programming languages in the world.
The C++ programming language was developed by Bjarne Stroustrup at Bell Labs in the 1980s, and was originally named "C with classes". The language was planned as an improvement on the C programming language, adding features based on object-oriented programming. Step by step, a lot of advanced features were added to the language, like operator overloading, exception handling and templates.
Help please!!(Include your modified DList.java source code file in.pdfjyothimuppasani1
Help please!!
(Include your modified DList.java source code file in your homework solution zip archive)
Using
whatever Java IDE you prefer, create a project and add DList.java and DListTest.java to it (these
files are provided
in the Week 6 Source zip archive). Modify DList to implement a method that removes all
occurrences of a specific
integer from the list. Here is the pseudocode:
Method removeAll(In: Integer pData) Returns Nothing
Define index variable i and initialize i to 0
While i < the size of this Dlist Do
If get(i) equals pData Then
remove(i)
Else
Increment i
End If
End While
End Method removeAll
Next, modify DListTest() to add test case 21 which tests that removeAll() works correctly.
WHat more do i need to provide to get help on this???
Solution
/* DListNode.java */
/**
* A DListNode is a node in a DList (doubly-linked list).
*/
class DListNode {
/**
* item references the item stored in the current node.
* prev references the previous node in the DList.
* next references the next node in the DList.
*
* DO NOT CHANGE THE FOLLOWING FIELD DECLARATIONS.
*/
public Object item;
protected DListNode prev;
protected DListNode next;
/**
* DListNode() constructor.
* @param i the item to store in the node.
* @param p the node previous to this node.
* @param n the node following this node.
*/
DListNode(Object i, DListNode p, DListNode n) {
item = i;
prev = p;
next = n;
}
}
/* DList.java */
/**
* A DList is a mutable doubly-linked list ADT. Its implementation is
* circularly-linked and employs a sentinel (dummy) node at the head
* of the list.
*
* DO NOT CHANGE ANY METHOD PROTOTYPES IN THIS FILE.
*/
class DList {
/**
* head references the sentinel node.
* size is the number of items in the list. (The sentinel node does not
* store an item.)
*
* DO NOT CHANGE THE FOLLOWING FIELD DECLARATIONS.
*/
protected DListNode head;
protected int size;
/* DList invariants:
* 1) head != null.
* 2) For any DListNode x in a DList, x.next != null.
* 3) For any DListNode x in a DList, x.prev != null.
* 4) For any DListNode x in a DList, if x.next == y, then y.prev == x.
* 5) For any DListNode x in a DList, if x.prev == y, then y.next == x.
* 6) size is the number of DListNodes, NOT COUNTING the sentinel,
* that can be accessed from the sentinel (head) by a sequence of
* \"next\" references.
*/
/**
* newNode() calls the DListNode constructor. Use this class to allocate
* new DListNodes rather than calling the DListNode constructor directly.
* That way, only this method needs to be overridden if a subclass of DList
* wants to use a different kind of node.
* @param item the item to store in the node.
* @param prev the node previous to this node.
* @param next the node following this node.
*/
protected DListNode newNode(Object item, DListNode prev, DListNode next) {
return new DListNode(item, prev, next);
}
/**
* DList() constructor for an empty DList.
*/
public DList() {
// Your solution here.
head = newNode(null, head, head);
head.prev = head;
head.next = head;
si.
20-13 Programming Project #05A Given the IntNode class- define the Fin.docxDavidxyNSimpsons
20.13 Programming Project #05A
Given the IntNode class, define the FindMax() function to return the largest value in the list or -99 if the list is empty. Assume all values in the list are non-negative.
Ex: If the list contains:
FindMax(headNode) returns 191.
Ex: If the list contains:
FindMax(headNode) returns -99.
**Please make sure returns -99 and not -1**
Given code:
main.cpp
#include <iostream>
using namespace std;
class IntNode {
public:
// Constructor
IntNode(int dataInit);
// Get node value
int GetNodeData();
// Get pointer to next node
IntNode* GetNext();
/* Insert node after this node.
Before: this -- next
After: this -- node -- next
*/
void InsertAfter(IntNode* newNode);
private:
int dataVal;
IntNode* nextNodePtr;
};
// Constructor
IntNode::IntNode(int dataInit) {
this->dataVal = dataInit;
nextNodePtr = nullptr;
}
// Get node value
int IntNode::GetNodeData() {
return this->dataVal;
}
// Get pointer to next node
IntNode* IntNode::GetNext() {
return this->nextNodePtr;
}
/* Insert node after this node.
Before: this -- next
After: this -- node -- next
*/
void IntNode::InsertAfter(IntNode* newNode) {
IntNode* tempNext = this->nextNodePtr;
this->nextNodePtr = newNode;
newNode->nextNodePtr = tempNext;
}
// Return largest value in the list
int FindMax(IntNode* headNode) {
/* Type your code here. */
}
int main() {
IntNode* headNode = new IntNode(-1);
IntNode* currNode;
IntNode* lastNode;
int max;
// Initiaize head node
lastNode = headNode;
// Add nodes to the list
for (int i = 0; i < 20; ++i) {
currNode = new IntNode(i);
lastNode->InsertAfter(currNode);
lastNode = currNode;
}
max = FindMax(headNode);
cout << "Max is " << max;
return 0;
}
.
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
}
/* ...
This is problem is same problem which i submitted on 22017, I just.pdffcaindore
There is a host of sociological and cultural research that paints a robust picture of the effects of
globalization on culture. This Application focuses on the flows of culture between Western and
developing nations. As a practitioner in this global environment, you should be familiar with
these culture effects. Use newspapers, magazines, and the Internet to research cultural changes in
both Western and developing countries due to globalization. Then perform the following tasks:
Outline the cultural aspects of globalization. Take an anthropological, rather than a business,
perspective. Explain how you think understanding culture helps in doing business in today\'s
global economy. Cite resources to justify your response.
Solution
Information technology has penetrated almost every aspect of our lives, “shrinking” our world
into a global village.
Economies and cultures have come closer. People are now aware of the cultures, traditions,
lifestyle, living conditions
prevailing in almost every corner of the world. Interestingly, this is going beyond awareness and
into a state of
integration that is a result of cross-pollinated views, ideologies, products and services.
This evolution is termed as “globalization.”
Culture has many definitions. My own definition is that culture is our collective experience as a
society,
and its impact on our reaction and decision-making relative to every-day facts and
circumstances.
Why is cross-cultural competence critical to your professional future and the viability of your
company?
It’s omnipresent in every business interaction and strategic decision.It is not feasible to be an
expert on
all the world’s cultures. It is possible, however, to incorporate a cross-cultural framework that
improves
cross-cultural understanding and interactions.
Multinational firms whose operations are borderless have to consider the cultural variability of
different regions
of the world and develop cultural understanding. Major cultural constraints encountered by
businesses include local
attitudes, taste preferences, language, religion, management style, gender discrimination, skills,
personalities,
education, etc. To be successful, they need to mold their business actions in accordance with the
local cultural models,
they need to establish a global mindset.
Let’s consider an example of the food giant, McDonald’s. The company enjoys a global
presence; operating in more than
100 countries serving 70 million people every day. Their headquarters and senior management
are U.S.-based but they
entrust their local operations to local managers of the countries they operate in. Operations in
more than 50 percent of
their outlets are franchised. Furthermore, their menus are customized according to cultural
habits and local taste
preferences in every country. It is without a doubt that global thinking and cultural
understanding are both powerful
business tools which allow multinational firms to dominate the local markets and establish a
global pres.
Need Help with this Java Assignment. Program should be done in JAVA .pdfarchiesgallery
Need Help with this Java Assignment. Program should be done in JAVA please
Complete required scripts based on eclipse and troubleshoot the scripts until the tasks are done.
1. Implement a binary search tree (write the code for it), for a height of 2 or higher. Please show
the output if you can Thank you in advance!
Solution
I have compiled this code and checked for errors, worked fine.
Also after the code I have pasted the Output transcript to show what User Inputs I gave and what
all outputs I got.
// Java Program to Implement Binary Tree
import java.util.Scanner;
/* Define Class BinaryTreeNode */
class BinaryTreeNode
{
BinaryTreeNode left, right;
int data;
/* Constructor */
public BinaryTreeNode()
{
left = null;
right = null;
data = 0;
}
/* Constructor */
public BinaryTreeNode(int n)
{
left = null;
right = null;
data = n;
}
/* Function to set left node */
public void setLeft(BinaryTreeNode n)
{
left = n;
}
/* Function to set right node */
public void setRight(BinaryTreeNode n)
{
right = n;
}
/* Function to get left node */
public BinaryTreeNode getLeft()
{
return left;
}
/* Function to get right node */
public BinaryTreeNode getRight()
{
return right;
}
/* Function to set data to node */
public void setData(int d)
{
data = d;
}
/* Function to get data from node */
public int getData()
{
return data;
}
}
/* Define anothe Class Operations to perform required operationns on Binary Tree*/
class Operations
{
private BinaryTreeNode root;
/* Constructor */
public Operations()
{
root = null;
}
/* Function to check if tree is empty */
public boolean isEmpty()
{
return root == null;
}
/* Functions to insert data */
public void insert(int data)
{
root = insert(root, data);
}
/* Function to insert data recursively */
private BinaryTreeNode insert(BinaryTreeNode node, int data)
{
if (node == null)
node = new BinaryTreeNode(data);
else
{
if (node.getRight() == null)
node.right = insert(node.right, data);
else
node.left = insert(node.left, data);
}
return node;
}
/* Function to count number of nodes */
public int countNodes()
{
return countNodes(root);
}
/* Function to count number of nodes recursively */
private int countNodes(BinaryTreeNode r)
{
if (r == null)
return 0;
else
{
int l = 1;
l += countNodes(r.getLeft());
l += countNodes(r.getRight());
return l;
}
}
/* Function to search for an element */
public boolean search(int val)
{
return search(root, val);
}
/* Function to search for an element recursively */
private boolean search(BinaryTreeNode r, int val)
{
if (r.getData() == val)
return true;
if (r.getLeft() != null)
if (search(r.getLeft(), val))
return true;
if (r.getRight() != null)
if (search(r.getRight(), val))
return true;
return false;
}
/* Function for inorder traversal */
public void inorder()
{
inorder(root);
}
private void inorder(BinaryTreeNode r)
{
if (r != null)
{
inorder(r.getLeft());
System.out.print(r.getData() +\" \");
inorder(r.getRight());
}
}
/* Function for preorder traversal */
public void preorder()
{
preorder(root);
}
priva.
Please i need help on following program using C++ Language.Add the.pdfezzi552
Instructions write a c program to solve the following problem. Upload your source code file to
Canvas. The file name must be of the form hwloop your name.c Substitute your first and last
name for \"your name\" in the file name. Example: Student\'s name is Sparky Watts. The file
name is hwloop sparky watts.c Problem Statement create a program that calculates twelve
month\'s interest and principle loan balance. Your program will ask the user for the starting
principle balance, annual interest rate, and monthly payment amount. Your program will verify
the input is reasonable, as described in the Error checking section below. After obtaining
reasonable the program will process 12 months of payments. The will show the accrued interest
and updated loan balance after each month\'s payment. The total interest paid and total payment
amounts for the 12 month period will also be calculated and displayed. Your program output
should resemble the output below. AUsers williidialDesktoplhw04MbinlDebuglhw04.exe Enter
loan anount: 32000.00 Enter annual interest rate 7.99 Enter monthly payment 752.84
Solution
#include
#include
int main()
{
double loan_amount = 0;
printf(\"Enter loan amount :\");
if (scanf(\"%lf\", &loan_amount) != 1)
{
printf(\"Please enter loan amount correctly\ \");
return -1;
}
if (loan_amount < 500)
{
printf(\"Loan amount should be greater than 500\ \");
return 1;
}
if (loan_amount > 100000)
{
printf(\"Loan amount should be less than 100000\ \");
return -1;
}
printf(\"Enter annual interest rate: \");
double interest_rate;
if (scanf(\"%lf\", &interest_rate) != 1)
{
printf(\"Please enter interest rate correctly\ \");
return -1;
}
if (interest_rate < 0 || interest_rate > 8.99)
{
printf(\"Interest rate should be in range of 0 to 8.99\ \");
return -1;
}
double monthly_payments;
printf(\"Enter monthly payment: \");
if (scanf(\"%lf\", &monthly_payments) != 1)
{
printf(\"Please monthly payment correctly\ \");
return -1;
}
double first_month_interest = (loan_amount * interest_rate)/(12*100);
if (monthly_payments < first_month_interest)
{
printf(\"Monthly payment should be greater than %f\ \", first_month_interest);
return -1;
}
double total_interest = 0;
double total_paid = 0;
printf(\"\ \");
printf(\"Begin \\t\\t\\t\\tMonthly\\tEnd\ \");
printf(\"Loan\\t\\tAccured\\t\\tPayment\\tLoan\ \");
printf(\"Balance\\t\\tInterest\\tAmount\\tBalance\ \");
printf(\"\ \");
int i;
for(i = 0; i <= 12; i++)
{
printf(\"%0.2f\\t\", loan_amount);
double interest = (loan_amount*interest_rate)/(1200);
printf(\"%0.2f\\t\\t\", interest);
printf(\"%0.2f\\t\", monthly_payments);
loan_amount = loan_amount + interest;
if (loan_amount < monthly_payments)
{
total_paid -= loan_amount;
loan_amount = 0;
printf(\"%0.2f\ \", loan_amount);
break;
}
else
{
loan_amount -= monthly_payments;
total_paid += monthly_payments;
}
printf(\"%0.2f\ \", loan_amount);
total_interest += interest;
}
printf(\"\ \");
printf(\"Annual total\\t%.2f\\t\\t%.2f\ \", total_interest, total_paid);
return 0;
}.
Assignment is Page 349-350 #4 and #5 Use the Linked Lis.pdfformicreation
Assignment is :
\"Page 349-350 #4 and #5 Use the \"Linked List lab\" you have been working on in class and add
the two functions the questions are asking you to develop: divideMid and divideAt. Be sure to
include comments Use meaningful identifier names (constants where appropriate) Do not work
together; no two people should have identical work!?!? Turn in .cpp file AND Turn in a \"print-
screen\' of your output (press \"print-screen\' on keyboard, then \'paste\' in MS-Word)\"
How do you solve QUESTION #5 in the book data structures using c++ by D.S. Malik in Visiual
Studios using the linked list below with what is being asked? Please need help
Linked list :
#include
#include
using namespace std;
struct nodeType
{
int info;
nodeType *link;
};
void createList(nodeType*& first, nodeType*& last);
void printList(nodeType*& first);
void insertFront(nodeType*& first);
void insertBack(nodeType*& last);
void deleteFirst(nodeType*& first);
void deleteLast(nodeType*& last, nodeType* first);
int main()
{
nodeType *first, *last;
int num;
createList(first, last);
int choice;
while(true)
{
cout<<\"1. Insert Front.\ 2. Insert Last.\ 3. Delete Front.\ 4. Delete Last.\ 5. Print List.\ 6. Exit.\
\";
cout<<\"Enter your choice: \";
cin>>choice;
switch(choice)
{
case 1: insertFront(first); break;
case 2: insertBack(last); break;
case 3: deleteFirst(first); break;
case 4: deleteLast(last, first); break;
case 5: printList(first); break;
case 6: return 0;
default: cout<<\"Invalid menu option. Try again.\"<>number;
while (number != -999)
{
newNode = new nodeType; // create new node
newNode->info = number;
newNode->link = NULL;
if (first == NULL)
{
first = newNode;
last = newNode;
}
else
{
last->link = newNode;
last = newNode;
}
cout<<\"Enter an integer (-999 to stop): \";
cin>>number;
} // end of while-loop
} // end of build list function
void deleteFirst(nodeType*& first)
{
nodeType *temp;
temp= first;
first= temp->link;
delete temp;
return;
}
void deleteLast(nodeType*& last, nodeType* current)
{
nodeType *temp;
while(current->link != NULL)
{
temp=current;
current=current->link;
}
temp=last;
current->link=NULL;
delete temp;
last = current;
return;
}
void insertFront(nodeType*& front)
{
int num;
cout<<\"\ Enter the number to insert: \";
cin>>num;
nodeType *newNode = new nodeType;
newNode->info=num;
newNode->link= front;
front= newNode;
return;
}
void insertBack(nodeType*& last)
{
int num;
cout<<\"\ Enter the number to insert: \";
cin>>num;
nodeType *newNode = new nodeType;
newNode->info=num;
newNode->link= NULL;
last->link= newNode;
last = newNode;
return;
}
void printList(nodeType*& first)
{
cout<<\"Inside printList...printing linked list...\ \"<info << \" \";
current = current->link;
}
cout<
#include
using namespace std;
struct nodeType
{
int info;
nodeType *link;
};
void createList(nodeType*& first, nodeType*& last);
void printList(nodeType*& first);
void insertFront(nodeType*& first);
void insertBack(nodeType*& last);
void deleteFirst(nodeType*& first);
void dele.
Similar to Assg 12 Binary Search Trees COSC 2336assg-12.cppAssg 12 Binary .docx (20)
Learning ResourcesRequired ReadingsToseland, R. W., & Ri.docxfestockton
Learning Resources
Required Readings
Toseland, R. W., & Rivas, R. F. (2017).
An introduction to group work practice
(8th ed.). Boston, MA: Pearson.
Chapter 11, “Task Groups: Foundation Methods” (pp. 336-363)
Chapter 12, “Task Groups: Specialized Methods” (pp. 364–395)
Van Velsor, P. (2009). Task groups in the school setting: Promoting children’s social and emotional learning.
Journal for Specialists in Group Work
,
34
(3), 276–292.
Document:
Group Wiki Project Guidelines (PDF)
Recommended Resources
Holosko, M. J., Dulmus, C. N., & Sowers, K. M. (2013). Social work practice with individuals and families: Evidence-informed assessments and interventions. Hoboken, NJ: John Wiley & Sons, Inc.
Chapter 1 “Assessment of Children”
Chapter 2 “Intervention with Children”
Discussion: Task Groups
Group work is a commonly used method within school settings. Because peer interaction is important in the emotional and social development of children, the task group can serve as a wonderful therapeutic setting and tool; however, many factors should be considered when implementing this type of intervention.
For this Discussion, read the Van Velsor (2009) article.
By Day 3
Post
your understanding of task groups as an intervention for children. Use the model for effective problem solving to compare and contrast (how to identify the problem, develop goals, collect data). How does this model differ from a traditional treatment group? What are the advantages and possible disadvantages of this model? Describe how you might use this model for adults. What populations would most benefit from this model?
.
LeamosEscribamos Completa el párrafo con las formas correctas de lo.docxfestockton
Leamos/Escribamos Completa el párrafo con las formas correctas de los verbos en paréntesis. Usa el pretérito o el imperfecto.
Yo __1__ (criarse) en el campo, pero mi familia __2__
(mudarse) a la ciudad cuando yo tenía doce años. Hablábamos
aymara en mi pueblo, y mi mamá no __3__ (expresarse) bien en
español. Mis hermanos y yo __4__ (comunicarse) sin problema
porque habíamos estudiado español en el colegio. Con dificultad
nosotros __5__ (acostumbrarse) al estilo de vida.Yo __6__
(preocuparse) por todo. No me __7__ (gustar) el ruido de los
carros. Pero poco a poco, nostros __8__ (asimilar) el modo de
ser de la gente de la cuidad.Yo __9__ (graduarse) de la
universidad hace poco, mi hermano mayor ahora es arquitecto, y
mi hermano menor __10__ (casarse) el mes pasado.
.
Leadership via vision is necessary for success. Discuss in detail .docxfestockton
Leadership via "vision" is necessary for success. Discuss in detail the qualities that a leader must exhibit in order to be considered visionary and, further, how these qualities may be learned and developed. Provide research and share insight on the determination of a specific leadership theory associated with leadership via vision. Cite your posting in proper APA format and ensure that your posting provides a minimum of 5 paragraphs.
.
Learning about Language by Observing and ListeningThe real.docxfestockton
Learning about Language by Observing and Listening
The real voyage of discovery consists not in seeking
new landscapes, but in having new eyes. Marcel Proust
The UCSD experience encompasses academic as well as social learning. Therefore, we learn not only from our courses, but from the people we meet on campus and the experiences we have with them. Life is a journey of self-discovery. As individuals, we are constantly seeking to determine who we are and where we belong in the world. Throughout this process, language is both a bridge and a barrier to communication and human growth.
The general subject matter for this essay is language or language communities. The source of your information will be what you observe and hear by listening to others. The goal is to do a project based on what our own minds can comprehend from diligent observation, note-taking, and reasoning. You should arrive at a reasoned (not emotional) conclusion. The conclusion/result of your experiment is your thesis and should be presented in the opening paragraph in one sentence. Secondary material should not be brought into this essay. Thus, this is not an essay that needs to be the result of academic texts or online sources. The research is what you see and how you interpret what you see and hear. It will be up to you to determine what particular focus your essay will take and wahat meaning you wish to convey to your reader. Do the exploratory writing activities on pages 73-76. These activities will guide you through an analysis of some of the reflections you completed in the first part of your book. Once you determine your focus, you will use the information you have already gathered and additional information you will research to clarify your ideas and provide evidence for the points you wish to make.
If you prefer a more direct prompt, the suggested topics listed below might be helpful to you. Choose one of the following topics to establish a focus and direction.
1) From your observations and conversations, what assumptions and stereotypes do we make about people based on language and behavior? What did you learn from the experiment?
2) You may examine body language as well as verbal language. Explore nonverbal communication in a group. What conclusions can you come to regarding the group based on nonverbal behavior?
3) Did you observe language differences between men and women here at UCSD Notice the ways in which men and women treat one another. Observe the language you hear on campus.
How do women greet one another? How do men greet each other? Do not just note the similarities or differences. Explain and interpret the information.
4) Observe and identify a code language on campus, on your job, or in your personal arena. How is language used? Is it effective? Analyze.
5) Have you become keenly aware of code switching? Who utilizes this language? In your observations and conversations, did you find code switching to be an acceptable form of lang.
Learning Accomplishment Profile-Diagnostic Spanish Language Edit.docxfestockton
Learning Accomplishment Profile-Diagnostic Spanish Language Edition
The Ages and Stages Questionnaires-Social Emotional (ASQ-SE)
Learning Accomplishment Profile-3 (LAP-3)
Mullen Scales of Early Learning
Purpose of the screening-what can an early childhood professional do with the results? What should happen next?
.
Learning about Language by Observing and ListeningThe real voy.docxfestockton
Learning about Language by Observing and Listening
The real voyage of discovery consists not in seeking
new landscapes, but in having new eyes. Marcel Proust
The UCSD experience encompasses academic as well as social learning. Therefore, we learn not only from our courses, but from the people we meet on campus and the experiences we have with them. Life is a journey of self-discovery. As individuals, we are constantly seeking to determine who we are and where we belong in the world. Throughout this process, language is both a bridge and a barrier to communication and human growth.
The general subject matter for this essay is language or language communities. The source of your information will be what you observe and hear by listening to others. The goal is to do a project based on what our own minds can comprehend from diligent observation, note-taking, and reasoning. You should arrive at a reasoned (not emotional) conclusion. The conclusion/result of your experiment is your thesis and should be presented in the opening paragraph in one sentence. Secondary material should not be brought into this essay. Thus, this is not an essay that needs to be the result of academic texts or online sources. The research is what you see and how you interpret what you see and hear. It will be up to you to determine what particular focus your essay will take and wahat meaning you wish to convey to your reader. Do the exploratory writing activities on pages 73-76. These activities will guide you through an analysis of some of the reflections you completed in the first part of your book. Once you determine your focus, you will use the information you have already gathered and additional information you will research to clarify your ideas and provide evidence for the points you wish to make.
If you prefer a more direct prompt, the suggested topics listed below might be helpful to you. Choose one of the following topics to establish a focus and direction.
1) From your observations and conversations, what assumptions and stereotypes do we make about people based on language and behavior? What did you learn from the experiment?
2) You may examine body language as well as verbal language. Explore nonverbal communication in a group. What conclusions can you come to regarding the group based on nonverbal behavior?
3) Did you observe language differences between men and women here at UCSD Notice the ways in which men and women treat one another. Observe the language you hear on campus.
How do women greet one another? How do men greet each other? Do not just note the similarities or differences. Explain and interpret the information.
4) Observe and identify a code language on campus, on your job, or in your personal arena. How is language used? Is it effective? Analyze.
5) Have you become keenly aware of code switching? Who utilizes this language? In your observations and conversations, did you find code switching to be an accepta.
LEARNING OUTCOMES1. Have knowledge and understanding of the pri.docxfestockton
LEARNING OUTCOMES:
1. Have knowledge and understanding of the principles of Constitutional and Administrative Law, and of the way in which these principles have developed.
2. Deal with issues relating to Constitutional and Administrative Law both systematically and creatively, recognising potential alternative conclusions for particular situations and providing supporting reasons for such conclusions.
3. Demonstrate self-direction and originality in tackling and solving problems relating to Constitutional and Administrative Law.
4. Research primary and secondary sources of Constitutional and Administrative Law.
5. Communicate thoughts and ideas in writing and/or orally, using the English language and legal terminology with care, clarity and accuracy.
6. Manage time effectively.
QUESTION:
A recently elected Government, concerned about rising gun crime by drug dealers, has introduced a Bill into Parliament to bring back the death penalty for any person convicted of causing death by the use of a firearm and which is also related to an illegal drug trade.
Human Rights UK (HRUK), part of a worldwide protest organisation called ‘Global Human Rights’ is opposed to the death penalty in any circumstances. HRUK has many thousands of members across the UK. The organisation is split into county groups and there is a thriving branch of over 1200 members in Penfield.
Sam Jones, the leader of the Penfield branch, has proposed a local demonstration against the Bill to take place on the 1
st
May 2014. The demonstration includes a march from the Town Hall in Penfield City Centre to the local War Memorial followed by speeches from senior members of the organisation.
The Chief Constable of Penfield Police, having been informed of the proposed protest is concerned about rumours that a small counter protest has been organised to disrupt the protest by a far right group opposed to human rights. He has issued a Notice to HRUK and Sam Jones under the Public Order Act 1986 which imposes the following conditions on the HRUK demonstration planned for 1
st
May 2014:-
Notice from the Chief Constable of Penfield Police:
1) any demonstration to be held by the HRUK between 1st March 2014 and 1
st
October 2014 should be held in Penfield Country Park, at least 25 miles from Penfield City Centre;
2) the maximum number of demonstrators shall be 25;
3) the maximum duration of the demonstration shall be 2 hours;
4) there should be no public speeches and;
5) that in the event of any counter demonstration or hostility shown towards HRUK members, the Penfield Police reserve the right to cancel the demonstration immediately
Advise, giving reasons, whether Sam Jones and/or HRUK can use the Human Rights Act 1998 to challenge the decision of the Chief Constable.
.
Leadership Style What do people do when they are leadingAssignme.docxfestockton
Leadership Style: What do people do when they are leading?
Assignment: Leadership Style: What Do People Do When They Are Leading?
Due Week 9 and worth 100 points
Choose one (1) of the following CEOs for this assignment: Ursula Burns (Xerox). Use the Internet to investigate the leadership style and effectiveness of the selected CEO.
Write a five to six (5-6) page paper in which you:
Provide a brief (one [1] paragraph) background of the CEO.
Analyze the CEO’s leadership style and philosophy, and how the CEO’s leadership style aligns with the culture.
Examine the CEO’s personal and organizational values.
Evaluate how the values of the CEO are likely to influence ethical behavior within the organization.
Determine the CEO’s three (3) greatest strengths and three (3) greatest weaknesses.
Select the quality that you believe contributes most to this leader’s success. Support your reasoning.
Assess how communication and collaboration, and power and politics influence group (i.e., the organization’s) dynamics.
Use at least five (5) quality academic resources in this assignment. Note: Wikipedia and other Websites do not qualify as academic resources.
Your assignment must follow these formatting requirements:
Be typed, double spaced, using Times New Roman font (size 12), with one-inch margins on all sides; citations and references must follow APA or school-specific format. Check with your professor for any additional instructions.
Include a cover page containing the title of the assignment, the student’s name, the professor’s name, the course title, and the date. The cover page and the reference page are not included in the required assignment page length.
The specific course learning outcomes associated with this assignment are:
Analyze the formation and dynamics of group behavior and work teams, including the application of power in groups.
Outline various individual and group decision-making processes and key factors affecting these processes.
Examine the primary conflict levels within organization and the process for negotiating resolutions.
Examine how power and influence empower and affect office politics, political interpretations, and political behavior.
Use technology and information resources to research issues in organizational behavior.
Write clearly and concisely about organizational behavior using proper writing me
.
Leadership Throughout HistoryHistory is filled with tales of leade.docxfestockton
Leadership Throughout History
History is filled with tales of leaders who were brave, selfless, and achieved glorious accomplishments. Your text discusses how leadership theory has been categorized throughout time, from the culture of ancient Egypt thousands of years ago, to the “toolbox” style of today.
The first category, known as the “Great Man” phase, focused on the traits that make an effective leader. This period ranges from circa 450 B.C. to the 1940s, and includes classic examples such as the aforementioned Egyptian period and the expansive influence of the Roman Empire.
The second category, known as the Behavior phase, spanned the 1940s to the 1960s, and focused on determining the types of behavior that leaders utilized to influence and affect others.
The final category is the Situational phase. This line of research began in the 1970s and is still present today. It suggests that leaders have a broad understanding of the various types of leadership styles, and can choose the appropriate one to handle a given situation.
I
n this Journal, discuss each phase, do research and provide examples of influential leaders from each phase, and explain how and why they were so influential.
Your Journal entry should be at least 500 words, and cite appropriate references in APA format.
.
Lean Inventory Management1. Why do you think lean inventory manage.docxfestockton
Lean Inventory Management
1. Why do you think lean inventory management can decrease transportation, capital expenses, and inventory storage?
2. List some products in your personal or family "inventory." How do you manage them? (For instance, do you constantly run to the store for milk? Do you throw out a lot of milk because of spoilage?) How can lean inventory change your way of managing these SKUs?
3. Identify a goods-producing or service-providing organization and discuss how it might make aggregate planning decisions.
4. Provide an argument for or against adopting a chase strategy for a major airline call center.
.
Leadership varies widely by culture and personality. An internationa.docxfestockton
Leadership varies widely by culture and personality. An international organization with locations in several countries must balance the local customs and cultures with those of the primary culture of the organizations’ headquarters. Using the Germany as the headquarters of an international Internet retail organization serving the USA and Canada research and discuss the differences that leaders would have to navigate in approach and adapting to different standards of behavior and culture within the countries.
.
Leadership is the ability to influence people toward the attainment .docxfestockton
Leadership is the ability to influence people toward the attainment of goals. The changing of the environment in which most organizations are operating has significantly influenced leadership systems in recent years, and has contributed to a shift in how we think about and practice leadership.
Analyze how leadership is changing in today’s organizations, including Level 5 leadership, servant leadership, and transformational leadership. Please discuss in 200-250 words.
.
Lawday. Court of Brightwaltham holden on Monday next after Ascension.docxfestockton
Lawday. Court of Brightwaltham holden on Monday next after Ascension Day in the twenty-first year of King Edward (A.D. 1293).
The tithingman of Conholt with his whole tithing present that all is well save that William of Mescombe has stopped up a . . . [the word is indecipherable in the manuscript, but Maitland thinks it is a watercourse] wrongfully. Therefore he is in mercy (12 d.). Also they say that Edith of Upton has cut down trees in the enclosure and the seisin of the lord contrary to a prohibition, and they say that she has no property and has fled into foreign parts, (amercement, 12 d.).
Adam Scot is made tithingman and sworn to a faithful exercise of his office.
John son of Hugh Poleyn enters on the land which Randolph Tailor held saving the right of everyone and gives for entry-money 4 marks and will pay 1 mark at Michaelmas in the twenty-second year of King Edward, 1 mark at Christmas next following, 1 mark at Easter, and 1 mark at Michaelmas next following, and for the due making of all these payments the said Hugh Poleyn finds sureties, to wit, Adam Scot, John Gosselyn, William of Mescombe, John Gyote. And because the said John is a minor the wardship of the said lands and tenements is delivered to his father the said Hugh Poleyn until he be of full age, on the terms of his performing the services due and accustomed for the same. Also there is granted to the said Hugh the crop now growing on the sown land, and the heriot due on this entry, for a half-mark payable at Michaelmas next on the security of the above-named sureties.
(a) Hugh Poleyn gives the lord 2 s. that he may have the judgment of the court as to his right in a certain tenement in Upton which J. son of Randolph Tailor claims as his right. And upon this the whole township of Brightwaltham sworn along with the whole township of Conholt say upon their oath that Hugh Poleyn has better right to hold the said tenement than anyone else has, and that he is the next heir by right of blood.
(The Conholt case as to the tenure of Edith wife of Robert Tailor according to the inquest made by the jurors. One Alan Poleyn held a tenement in Conholt upon servile terms and had a wife Cristina by name. The said Alan died when Richard was the farmer [of the manor]. Thereupon came the friends of the said Cristina and procured for her a part of the land by way of dower making a false suggestion and as though [the land] were of free condition, and this was to the great prejudice of the lord Abbot. Upon this came one Richard Aleyn and espoused the said Cristina and begot upon her one Randolph. Then Richard died, and the said Cristina of her own motion enfeoffed Randolph her son of the said tenement. Then Cristina died, and Randolph being in seisin of the said tenement espoused Edith the present demanding; and after Randolph's death Edith married Robert Tailor. Now you can see and give your counsel about the right of the said Edith. And know this, that if I had at hand the court-rolls of the.
Leaders face many hurdles when leading in multiple countries. There .docxfestockton
Leaders face many hurdles when leading in multiple countries. There are several examples of disastrous public relations fallout that have occurred when companies have outsourced work to other nations. When determining where to move offshore as a company, the leaders of the organization must make several decisions.
Using course theories and current multinational organizations that have locations in several countries, convey your own thoughts on the subject and address the following:
What leadership considerations must an organization weigh in selecting another country to open a location such as a manufacturing plant?
How might leaders need to change leadership styles to manage multinational locations?
What public relations issues might arise from such a decision?
How would you recommend such a company to demonstrate their social responsibility to their headquarters country as well as any offshore locations?
.
Last year Angelina Jolie had a double mastectomy because of re.docxfestockton
Last year Angelina Jolie had a double mastectomy because of results from a genetic test. Describe the science of the test and the reason for her decision. Do you agree with her choice, and do you agree with her decision to go public about her choice?
1 page essay with at least 1 reference
.
Leaders face many hurdles when leading in multiple countries. Ther.docxfestockton
Leaders face many hurdles when leading in multiple countries. There are several examples of disastrous public relations fallout that have occurred when companies have outsourced work to other nations. When determining where to move offshore as a company, the leaders of the organization must make several decisions.
Using course theories and current multinational organizations that have locations in several countries, convey your own thoughts on the subject and address the following:
What leadership considerations must an organization weigh in selecting another country to open a location such as a manufacturing plant?
How might leaders need to change leadership styles to manage multinational locations?
What public relations issues might arise from such a decision?
How would you recommend such a company to demonstrate their social responsibility to their headquarters country as well as any offshore locations?
Please submit your assignment.
This assignment will be assessed using the rubric provided
here
.
For assistance with your assignment, please use your text, Web resources, and all course materials.
.
Leaders today must be able to create a compelling vision for the org.docxfestockton
Leaders today must be able to create a compelling vision for the organization. They also must be able to create an aligned strategy and then execute it. Visions have two parts, the envisioned future and the core values that support that vision of the future. The ability to create a compelling vision is the primary distinction between leadership and management. Leaders need to create a vision that will frame the decisions and behavior of the organization and keep it focused on the future while also delivering on the short-term goals.
Respond to the following:
Assess your current leaders. These leaders could be those at your current or previous organizations or your educational institutions.
How effective are they at creating and communicating the organization vision?
How effective are they at developing a strategy and communicating it throughout the organization?
How effective are they at upholding the values of the organization?
Support your positions with specific examples or by citing credible sources.
.
Law enforcement professionals and investigators use digital fore.docxfestockton
Law enforcement professionals and investigators use digital forensic methods to solve crimes every day. Locate one current news article that explains how investigators may have used these techniques to solve a crime. Explain the crime that was solved, and the methods used to determine how the crime was committed. Some examples of crimes solved may include locating missing children, finding criminals who have fled the scene of a crime, or unsolved crimes from the past that have been solved due to the use of new techniques (such as DNA testing).
Your written assignment should be 3-4 paragraphs in your own words and should include a reference citation for your source of information.
.
LAW and Economics 4 questionsLaw And EconomicsTextsCoote.docxfestockton
LAW and Economics 4 questions
Law And Economics
Texts
Cooter, Robert and Thomas Ulen. 2011. Law and Economics. Sixth Edition. Boston: Pearson Addison Wesley
(Chapter 1-4)
Polinksky, A. Mitchell. 2011. An Introduction to Law and Economics. Fourth Edition. New York: Aspen Publishers.
(Chapters 1-2)
Posner, Richard A. 2007. Economic Analysis of Law. Seventh Edition. Boston: Little, Brown and Company.
(Chapter 1)
2.) Discuss the adverse impacts of monopoly upon market outcomes. Discuss the impact of government’s monopoly power over coercion.
6.) Suppose the local government determines that the price of food is too high and imposes a ceiling on the market price of food that is below the equilibrium price in that locality. Predict some of the consequences of the ceiling.
10.) Consider the right to smoke or to be free from smoke in the following situations:
1. smoking in a public area.
2. smoking in hotel rooms.
3. smoking in a private residence.
4. smoking on commercial airline flights.
In which situations do you think the transaction costs are so high that they
preclude private bargaining. In what cases are they low enough to allow private
bargains to occur? Explain your answer
14.)From an economic point of view, why is stare decisis an important rule of
decision making for the courts?
.
Model Attribute Check Company Auto PropertyCeline George
In Odoo, the multi-company feature allows you to manage multiple companies within a single Odoo database instance. Each company can have its own configurations while still sharing common resources such as products, customers, and suppliers.
The Art Pastor's Guide to Sabbath | Steve ThomasonSteve Thomason
What is the purpose of the Sabbath Law in the Torah. It is interesting to compare how the context of the law shifts from Exodus to Deuteronomy. Who gets to rest, and why?
Instructions for Submissions thorugh G- Classroom.pptxJheel Barad
This presentation provides a briefing on how to upload submissions and documents in Google Classroom. It was prepared as part of an orientation for new Sainik School in-service teacher trainees. As a training officer, my goal is to ensure that you are comfortable and proficient with this essential tool for managing assignments and fostering student engagement.
How to Create Map Views in the Odoo 17 ERPCeline George
The map views are useful for providing a geographical representation of data. They allow users to visualize and analyze the data in a more intuitive manner.
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.
Unit 8 - Information and Communication Technology (Paper I).pdfThiyagu K
This slides describes the basic concepts of ICT, basics of Email, Emerging Technology and Digital Initiatives in Education. This presentations aligns with the UGC Paper I syllabus.
This is a presentation by Dada Robert in a Your Skill Boost masterclass organised by the Excellence Foundation for South Sudan (EFSS) on Saturday, the 25th and Sunday, the 26th of May 2024.
He discussed the concept of quality improvement, emphasizing its applicability to various aspects of life, including personal, project, and program improvements. He defined quality as doing the right thing at the right time in the right way to achieve the best possible results and discussed the concept of the "gap" between what we know and what we do, and how this gap represents the areas we need to improve. He explained the scientific approach to quality improvement, which involves systematic performance analysis, testing and learning, and implementing change ideas. He also highlighted the importance of client focus and a team approach to quality improvement.
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!
Assg 12 Binary Search Trees COSC 2336assg-12.cppAssg 12 Binary .docx
1. 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 pro
gram
* 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 starte
d
* the program.
* @param argv The command line arguments, an array of chara
cter
* arrays.
*
* @returns An int value indicating program exit status. Usuall
2. y 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;
4. }
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 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
5. 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
6. 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
7. 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 return the newly created
BinaryTreeNode as
a result from the insert() function (notice that the private
insert()
should always return a BinaryTreeNode*). This is because,
when a
new node is allocated, it gets returned and it needs to be
assigned to
something so it gets inserted into the tree. For example, think of
what
happens initially when the BinaryTree is empty. In that case the
root
of the tree will be NULL. When you call the recursive insert()
on the
initially empty tree, you need to assign the returned value back
into
2
root in the non-recursive function (and you also need to
increment the
nodeCount by 1 in your public non-recursive function).
8. The general cases for the recursion are as follows. Since we are
imple-
menting a binary search tree, we need to keep the tree
organized/sorted.
Thus in the general case, remember that we have already tested
that
the node is not NULL, thus there is an item in the node->item.
So for
the general case, if the item we are inserting is less than or
equal to
node->item, then we need to insert it into the left child subtree
(it
is important to use <= comparison to determine if to go left
here). To
do this you will basically just call insert() recursively with the
item
to be inserted, and passing in node->left as the �rst parameter.
Of
course, in the case that the item is greater than the one in the
cur-
rent node, you instead need to call insert() on the node->right
child
subtree.
And �nally, make sure you take care of correctly returning a
result
from the recursive insert(). Here when you call insert() on ei-
ther the left or right child subtree, the function should return a
BinaryTreeNode*. For example, imagine that you are inserting
into
the left child, and there is no left subtree, and thus left will be
NULL. In that case the recursive call to insert() will create a
new node
dynamically and return it. So the return value from calling
insert()
needs to be assiged back into something. If you are calling
9. insert()
on the left child, the returned result should be assigned back
into
node->left, and if you are calling on the right child, the returned
re-
sult should be assigned back into node->right. Again this is
because
when we �nally �nd where the node needs to be linked into the
tree,
we will do it at either an empty left or right subtree child. Thus
in order to link the newly created node into the tree, we need to
as-
sign the returned pointer back into either node->left or node-
>right
appropriately. And �nally, after you call insert() recursively in
the
general case, you do have to remember that you always have to
return
a BinaryTreeNode*. For the base case, when you dynamically
create
a new node, the new node is what you return. But in the general
case,
you should simply return the current node. This will get
(re)assigned
when you return back to the parent, but this is �ne and
expected.
To summarize, you need to do the following to implement the
insert()
functionality:
� The public insert() should simply call the private insert() on
3
10. the root node.
� In the public insert() the return result should be assigned
back
into root.
� The public insert() is also responsible for incrementing the
nodeCount
member variable.
� For the private recursive insert() the base case occurs when a
NULL node is received, in which case a new BinaryTreeNode is
dynamically created and returned.
� For the general case, if node is not NULL, then you instead
either
need to call insert() recursively on the left or right subchild,
depending on if the item to be inserted is <= or > the node-
>item
respectively.
� Don't forget in the general case, that the returned result from
calling insert() needs to be assigned back into left or right as
appropriate.
� And �nally, the recursive insert() always returns a value, and
in the general case you should simply just return the node as the
result.
2. Next we have a relatively easier set of tasks to accomplish.
Once
you have insert() working and tested, we will implement a
function
to determine the current height() of the tree. You should read
our
11. textbook to make sure you know the de�nition of the height of
a tree.
height() needs 2 functions again, a public function which is the
in-
terface, and a private function that is recursive and does the
actual
work. Both the public and private height() functions should be
de-
clared as const functions, as they do not actually modify the
contents
of the tree. Both functions return an int result. The public
function
doesn't have any input parameters, but the private function
should
take a single BinaryTreeNode* as its input parameter.
The public height() function should be very simply, it should
simply
call the private height() on the root node of the binary tree, and
return the resulting calculated height.
For the private height() function, the base case is that if node is
NULL
then the height is 0, so you should return 0 in that case.
Otherwise,
in the general case, the height is conceptuall 1 plus the height
of the
bigger of the heights of the two subtree children left and right.
Thus
4
to calculate the height for a given node, recursive calculate
12. height on
both the left and right children, �nd the maximum of these two,
add
1 to it, and that is the height of the node.
3. The third and �nal task is to implement the clear() abstract
function.
The clear() function basically clears out all of the stored items
from
the tree, deallocating and returning the memory used for the
node
storage back to the OS.
As with all of the functions for this assignment, clear() needs
both
a public function that acts as the interface, and a private
recursive
version that does all of the work. The implementation of the
pub-
lic clear() is almost as simple as the previous height() function.
The public clear() should simply call the private clear(), passing
in the current root of the tree. Both the public and private
versions
of clear() should be void functions, they do not return any result
or
value.
The private recursive clear() is a void function, as we
mentioned,
and it takes a single BinaryTreeNode* parameter as its input.
This
function is also relatively rather easy. The base case is that, if
node is
NULL then you don't have to do anything, simply return, as you
have
reached the end of the recursion in that case. For the general
13. case,
all you need to do is simply call clear() recursively on the left
and
right subtree children �rst. Then after this you can safely call
delete
on the node, because all of the nodes in the two subtree children
will
have been deleted by the recursion, and now you can safely
delete and
free up the memory for the node.
In this assignment you will only be given 3 �les in total. The
"assg-
12.cpp" �le contains tests of the BinaryTree insert(), height()
and clear()
functions you are to implement. You will also be given
"BinaryTree.hpp"
which is a header �le containing the de�nition of the
BinaryTreeNode struc-
ture and BinaryTree class, including initial implementations for
constructors
and for displaying the tree as a string.
Here is an example of the output you should get if your code is
passing
all of the tests and is able to run the simulation. You may not
get the
exact same statistics for the runSimulation() output, as the
simulation is
generating random numbers, but you should see similar values.
--------------- testing BinaryTree construction ----------------
<constructor> Size of new empty tree: 0
5
14. size: 0 items: [ ]
--------------- testing BinaryTree insertion -------------------
<insert> Inserted into empty tree, size: 1
size: 1 items: [ 10 ]
<insert> inserted 5 more items, size: 6
size: 6 items: [ 2 3 7 10 12 15 ]
--------------- testing BinaryTree height -------------------
<height> Current tree height: 3
<height> after inserting nodes, height: 5 size: 8
size: 8 items: [ 2 3 4 5 7 10 12 15 ]
--------------- testing BinaryTree clear -------------------
<clear> after clearing tree, height: 0 size: 0
size: 0 items: [ ]
Assignment Submission
A MyLeoOnline submission folder has been created for this
assignment. You
should attach and upload your completed
"BinaryTree.[hpp|cpp]" source �les
to the submission folder to complete this assignment. You do
15. not need to
submit your "assg-12.cpp" �le with test. But please only submit
the asked
for source code �les, I do not need your build projects,
executables, project
�les, etc.
Requirements and Grading Rubrics
Program Execution, Output and Functional Requirements
1. Your program must compile, run and produce some sort of
output to
be graded. 0 if not satis�ed.
2. (40 pts.) insert() functionality is implemented correctly. Base
and
general cases are written as described. Functions work for trees
with
items and when tree is empty.
6
3. (30 pts.) height() functionality is implemented correctly.
Correctly
implement stated base and general cases using recursion.
4. (30 pts.) clear() functionality is implemented correctly.
Correctly
implement stated base and general cases using recursion.
5. (5 pts. extra credit) Of course it is not really useful to have a
BinaryTree
container that can only handle int types. Templatize your
16. working
class so it works as a container for any type of object. If you do
this,
please make a new version of "assg-12.cpp" that works for your
tem-
platized version, passes all of the tests for an <int> container,
and add
tests for a di�erent type, like <string>.
6. (5 pts. extra credit) Implement a printTree() method. The
tostring()
method I gave you doesn't really show the structure of the tree.
Of
course if you had a graphical environment you could draw a
picture of
the tree. But if you only have a terminal for output, you can
display
the tree as a tree on its side relatively easy. To do this, you need
again
both a public and private printTree() method. The private
method is
the recursive implementation, and as usual it takes a
BinaryTreeNode*
as a parameter, and a second parameter indicate the o�set or
height of
this node in the tree. If you perform a reverse preorder traversal
of the
tree, spacing or tabbing over according to the tree height, then
you can
display the approximate structure of the tree on the terminal.
Recall
that preorder traversal is performed by visiting left, then
ourself, then
our right child. So a reverse preorder is performed by �rst
visiting our
right, then ourself, then our left child.
17. 7. (10 pts. extra credit) The BinaryTree is missing a big piece of
fun-
cionality, the ability to remove items that are in the tree. You
can read
our textbook for a description of how you can implement
functions to
remove items from the tree. It is a good exercise, and quite a bit
more
challenging than the insert(). The simplest case is if you want to
remove a node that is a leaf node (both left and right are NULL,
indicating no child subtrees). When removing a leaf, you can
simply
delete the node and set the parent pointer in the tree to this node
to
NULL. When the node only has 1 subtree, either the left or the
right,
you can also still do something relatively simple to assign the
orphaned
subtree back to the parent, then delete the node with the item
that is
to be removed. But when the node to be deleted also has both
left
and right child subtrees, then you need to do some
rearrangements
7
of the tree. The Sha�er textbook discusses how to implement
removal
from a binary tree as an example you can follow.
Program Style
18. Your programs must conform to the style and formatting
guidelines given
for this class. The following is a list of the guidelines that are
required for
the assignment to be submitted this week.
1. Most importantly, make sure you �gure out how to set your
indentation
settings correctly. All programs must use 2 spaces for all
indentation
levels, and all indentation levels must be correctly indented.
Also all
tabs must be removed from �les, and only 2 spaces used for
indentation.
2. A function header must be present for member functions you
de�ne.
You must give a short description of the function, and document
all of
the input parameters to the function, as well as the return value
and
data type of the function if it returns a value for the member
functions,
just like for regular functions. However, setter and getter
methods do
not require function headers.
3. You should have a document header for your class. The class
header
document should give a description of the class. Also you
should doc-
ument all private member variables that the class manages in
the class
document header.
4. Do not include any statements (such as system("pause") or
19. inputting
a key from the user to continue) that are meant to keep the
terminal
from going away. Do not include any code that is speci�c to a
single
operating system, such as the system("pause") which is
Microsoft
Windows speci�c.
8
Assg 12 Binary Search Trees COSC 2336/BinaryTree.cppAssg
12 Binary Search Trees COSC 2336/BinaryTree.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<iostream>
#include<string>
#include<sstream>
#include"BinaryTree.hpp"
usingnamespace std;
/** BinaryTree default constructor
* Default constructor for a BinaryTree collection. The default
* behavior is to create an initially empty tree with no
* items currently in the tree.
*/
20. BinaryTree::BinaryTree()
{
root = NULL;
nodeCount =0;
}
/** BinaryTree destructor
* The destructor for a BinaryTree. Be a good manager of mem
ory
* and make sure when a BinaryTree goes out of scope we free
* up all of its memory being managed. The real work is done
* by the clear() member function, whose purpose is exactly this
,
* to clear all items from the tree and return it back to an
* empty state.
*/
BinaryTree::~BinaryTree()
{
// uncomment this after you implement clear in step X, to ensure
// when trees are destructed that all memory for allocated nodes
// is freed up.
//clear();
}
/** BinaryTree size
* Return the current size of this BinaryTree. Here size means t
he
* current number of nodes/items currently being managed by th
e
* BinaryTree.
*
* @returns int Returns the current size of this BinaryTree.
*/
intBinaryTree::size()const
21. {
return nodeCount;
}
/** BinaryTree tostring
* This is the recursive private function that does the actual
* work of creating a string representation of the BinaryTree.
* We perform a (recursive) inorder traversal, constructing a
* string object, to be returned as a result of this function.
*
* @param node The BinaryTreeNode we are currently processi
ng.
*
* @returns string Returns the constructed string of the BinaryT
ree
* contents in ascending sorted order.
*/
string BinaryTree::tostring(BinaryTreeNode* node)const
{
// base case, if node is null, just return empty string, which
// stops the recursing
if(node == NULL)
{
return"";
}
// general case, do an inorder traversal and build tring
else
{
ostringstream out;
// do an inorder traversal
out << tostring(node->left)
<< node->item <<" "
<< tostring(node->right);
22. return out.str();
}
}
/** BinaryTree tostring
* Gather the contents and return (for display) as a string.
* We use an inorder traversal to get the contents and construct
* the string in sorted order. This function depends on operator
<<
* being defined for the item type being held by the BinaryTree
Node.
* This function is actually only the public interface, the
* actual work is done by the private recursive tostring() functio
n.
*
* @returns string Returns the constructed string of the BinaryT
ree
* contents in ascending sorted order.
*/
string BinaryTree::tostring()const
{
ostringstream out;
out <<"size: "<< nodeCount
<<" items: [ "<< tostring(root)<<"]"<< endl;
return out.str();
}
/** BinaryTree output stream operator
* Friend function for BinaryTree, overload output stream
* operator to allow easy output of BinaryTree representation
* to an output stream.
*
23. * @param out The output stream object we are inserting a strin
g/
* representation into.
* @param aTree A reference to the actual BinaryTree object to
be
* displayed on the output stream.
*
* @returns ostream Returns reference to the output stream after
* we insert the BinaryTree contents into it.
*/
ostream&operator<<(ostream& out,constBinaryTree& aTree)
{
out << aTree.tostring();
return out;
}
Assg 12 Binary Search Trees COSC 2336/BinaryTree.hpp
/**
* @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 <string>
using namespace std;
/** Binary Tree Node
* A binary tree node, based on Shaffer binary tree node ADT,
24. pg. 156.,
* implementation pg. 161. The node class is not the tree. A
binary
* search tree consists of a structure/colleciton of binary tree
nodes,
* arranged of course as a binary tree. A binary tree nodes
purpose is to
* store the key/value of a single item being managed, and to
keep links
* to left and right children.
*
* We assume both key and value are the same single item here.
This
* version is not templatized, we create nodes that hold simple
int
* values, but we could parameritize this to hold arbitrary value
* types.
*
* @value item The item held by this binary tree node. This
item is
* both the key and the value of the item being stored. In
* alternative implementations we might want to split the key
and
* value into two separate fields.
* @value left, right Pointers to the left child and right child
nodes
* of this node. These can be null to indicate that not left/right
* child exists. If both are null, then this node is a leaf node.
*/
struct BinaryTreeNode
{
int item;
BinaryTreeNode* left;
BinaryTreeNode* right;
};
25. /** Binary Tree
* A binary search tree implementation, using pointers/linked
list, based
* on Shaffer example implementation pg. 171. This is the class
that
* actually manages/implements the tree. It contains a single
* pointer to the root node at the top (or bottom depending on
how you
* view it) of the tree. We also maintain a count of the number
of nodes
* currently in the tree. This class will support insertion
* and searching for new nodes.
*
* @value root A pointer to the root node at the top of the
* tree. When the tree is initially created and/or when the tree
is
* empty then root will be null.
* @value nodeCount The count of the number of nodes/items
currently in
* this binary tree.
*/
class BinaryTree
{
private:
BinaryTreeNode* root;
int nodeCount;
// private helper methods, do actual work usually using
recursion
string tostring(BinaryTreeNode* node) const;
public:
// constructors and destructors
BinaryTree();
~BinaryTree();
26. // accessor methods
int size() const;
// insertion, deletion and searching
// tree traversal and display
string tostring() const;
friend ostream& operator<<(ostream& out, const BinaryTree&
aTree);
};