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 == .
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 ...
Tree Traversals A tree traversal is the process of visiting.pdfajayadinathcomputers
Tree Traversals
A tree traversal is the process of "visiting" each node of a tree in some particular order. For a
binary search tree, we can talk about an inorder traversal and a preorder traversal. For this
assignment you are to implement both of these traversals in the code that was started in class.
File bstree.h contains the BSTree class that was developed during class (with the addition of
comments which were omitted by your instructor due to time constraints). The class contains two
inorder functions, one public and one private, and two preorder functions, also one public and one
private. As was the case with other functions implemented for this class, the public versions of
these functions simply call the private versions passing the root node (pointer) as a parameter.
The private versions carry out their actions on the subtree rooted at the given node.
The code provided in bstree.h is missing the implementations for the private inorder and preorder
functions. The coding part of this assignment is to implement these two functions.
When completed, the test program provided should produce the following output:
Values stored in the tree are:
bird
cat
deer
dog
giraffe
groundhog
horse
snake
turtle
The structure of the tree is as follows:
dog
-bird
--cat
---deer
-turtle
--giraffe
---snake
----groundhog
-----horse
Copied!
Written Part
In addition to the coding noted above, give an analysis of all public member functions of the class,
including all constructors, the destructor, and the overload of the assignment operator. For your
analysis you may assume a well-balanced tree (whereas a lopsided tree might lead to a different
analysis).
bstree.h
#pragma once
// A Binary Search Tree implementation.
template <typename T>
class BSTree {
private:
// A node in the tree. Each node has pointers to its left and right nodes
// as well as its parent. When a node is created, the parent and data item
// must be provided.
class node {
public:
T data;
node* left;
node* right;
node* parent;
node (const T& d, node* p) {
parent = p;
data = d;
left = right = nullptr;
}
};
// Pointer to the root node. Initially this is null for an empty tree.
node* root;
// Copy the subtree of another BSTree object into this object. Used by
// the copy constructor and assignment operator.
void copy (node* p) {
if (p) { // If p points to a node...
insert(p->data); // Insert data item
copy(p->left); // Copy the left subtree
copy(p->right); // Copy the right subtree
}
}
// Destroy a node and all nodes in both subtrees. Called by the
// destructor.
void destroy (node* p) {
if (p) { // If p is not null...
destroy(p->left); // Destroy the left subtree
destroy(p->right); // Destroy the right subtree
delete p; // Destroy the node
}
}
// Helper function to determine if a data value is contained in the tree.
// Takes the data value being searched and a pointer to the node in the
// tree. Returns pointer to node in which data item is found, a null
// pointer otherwise.
node* find (const T& .
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
}
/* ...
Thisi s a program of a binary tree which is extended from its super class Simple Tree. It uses all the functionalities from its super class. A binary tree consists of two leaves mainly left child nodes and right child nodes.
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.
Add these three functions to the class binaryTreeType (provided).W.pdfindiaartz
Add these three functions to the class binaryTreeType (provided).
Write the definition of the function, nodeCount, that returns the number of nodes in the binary
tree.
Write the definition of the function, leavesCount, that takes as a parameter a pointer to the root
node of a binary tree and returns the number of leaves in a binary tree.
Write a function, swapSubtrees, that swaps all of the left and right subtrees of a binary tree. Print
the original tree and the resulting tree using a pre-order traversal.
Write a program to test your new functions. Use the data provided to build your binary search
tree (-999 is the sentinel): (C++)
Data: 65 55 22 44 61 19 90 10 78 52 -999
Already completed code is below:
//Header File Binary Search Tree
#ifndef H_binarySearchTree
#define H_binarySearchTree
#include \"binaryTree.h\"
#include
using namespace std;
template
class bSearchTreeType: public binaryTreeType
{
public:
bool search(const elemType& searchItem) const;
//Function to determine if searchItem is in the binary
//search tree.
//Postcondition: Returns true if searchItem is found in
// the binary search tree; otherwise,
// returns false.
void insert(const elemType& insertItem);
//Function to insert insertItem in the binary search tree.
//Postcondition: If there is no node in the binary search
// tree that has the same info as
// insertItem, a node with the info
// insertItem is created and inserted in the
// binary search tree.
void deleteNode(const elemType& deleteItem);
//Function to delete deleteItem from the binary search tree
//Postcondition: If a node with the same info as deleteItem
// is found, it is deleted from the binary
// search tree.
// If the binary tree is empty or deleteItem
// is not in the binary tree, an appropriate
// message is printed.
private:
void deleteFromTree(nodeType* &p);
//Function to delete the node to which p points is
//deleted from the binary search tree.
//Postcondition: The node to which p points is deleted
// from the binary search tree.
};
template
bool bSearchTreeType::search
(const elemType& searchItem) const
{
nodeType *current;
bool found = false;
if (this->root == NULL)
cout << \"Cannot search an empty tree.\" << endl;
else
{
current = this->root;
while (current != NULL && !found)
{
if (current->info == searchItem)
found = true;
else if (current->info > searchItem)
current = current->lLink;
else
current = current->rLink;
}//end while
}//end else
return found;
}//end search
template
void bSearchTreeType::insert
(const elemType& insertItem)
{
nodeType *current; //pointer to traverse the tree
nodeType *trailCurrent; //pointer behind current
nodeType *newNode; //pointer to create the node
newNode = new nodeType;
newNode->info = insertItem;
newNode->lLink = NULL;
newNode->rLink = NULL;
if (this->root == NULL)
this->root = newNode;
else
{
current = this->root;
while (current != NULL)
{
trailCurrent = current;
if (current->info == insertItem)
{
cout << \"The item to be inserted is already \";
cout << \"in the t.
Assg 12 Binary Search Trees COSC 2336assg-12.cppAssg 12 Binary .docxfestockton
Assg 12 Binary Search Trees COSC 2336/assg-12.cppAssg 12 Binary Search Trees COSC 2336/assg-12.cpp/**
* @author Jane Programmer
* @cwid 123 45 678
* @class COSC 2336, Spring 2019
* @ide Visual Studio Community 2017
* @date April 8, 2019
* @assg Assignment 12
*
* @description Assignment 12 Binary Search Trees
*/
#include<cassert>
#include<iostream>
#include"BinaryTree.hpp"
usingnamespace std;
/** main
* The main entry point for this program. Execution of this program
* will begin with this main function.
*
* @param argc The command line argument count which is the number of
* command line arguments provided by user when they started
* the program.
* @param argv The command line arguments, an array of character
* arrays.
*
* @returns An int value indicating program exit status. Usually 0
* is returned to indicate normal exit and a non-zero value
* is returned to indicate an error condition.
*/
int main(int argc,char** argv)
{
// -----------------------------------------------------------------------
cout <<"--------------- testing BinaryTree construction ----------------"<< endl;
BinaryTree t;
cout <<"<constructor> Size of new empty tree: "<< t.size()<< endl;
cout << t << endl;
assert(t.size()==0);
cout << endl;
// -----------------------------------------------------------------------
cout <<"--------------- testing BinaryTree insertion -------------------"<< endl;
//t.insert(10);
//cout << "<insert> Inserted into empty tree, size: " << t.size() << endl;
//cout << t << endl;
//assert(t.size() == 1);
//t.insert(3);
//t.insert(7);
//t.insert(12);
//t.insert(15);
//t.insert(2);
//cout << "<insert> inserted 5 more items, size: " << t.size() << endl;
//cout << t << endl;
//assert(t.size() == 6);
cout << endl;
// -----------------------------------------------------------------------
cout <<"--------------- testing BinaryTree height -------------------"<< endl;
//cout << "<height> Current tree height: " << t.height() << endl;
//assert(t.height() == 3);
// increase height by 2
//t.insert(4);
//t.insert(5);
//cout << "<height> after inserting nodes, height: " << t.height()
// << " size: " << t.size() << endl;
//cout << t << endl;
//assert(t.height() == 5);
//assert(t.size() == 8);
cout << endl;
// -----------------------------------------------------------------------
cout <<"--------------- testing BinaryTree clear -------------------"<< endl;
//t.clear();
//cout << "<clear> after clearing tree, height: " << t.height()
// << " size: " << t.size() << endl;
//cout << t << endl;
//assert(t.size() == 0);
//assert(t.height() == 0);
cout << endl;
// return 0 to indicate successful completion
return0;
}
Assg 12 Binary Search Trees COSC 2336/assg-12.pdf
Assg 12: Binary Search Trees
COSC 2336 Spring 2019
April 10, 2019
Dates:
Due: Sunday April 21, by Midnight
Objectives
� Practice recursive algorithms
� Learn how to construct a binary tree usi ...
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 ...
Tree Traversals A tree traversal is the process of visiting.pdfajayadinathcomputers
Tree Traversals
A tree traversal is the process of "visiting" each node of a tree in some particular order. For a
binary search tree, we can talk about an inorder traversal and a preorder traversal. For this
assignment you are to implement both of these traversals in the code that was started in class.
File bstree.h contains the BSTree class that was developed during class (with the addition of
comments which were omitted by your instructor due to time constraints). The class contains two
inorder functions, one public and one private, and two preorder functions, also one public and one
private. As was the case with other functions implemented for this class, the public versions of
these functions simply call the private versions passing the root node (pointer) as a parameter.
The private versions carry out their actions on the subtree rooted at the given node.
The code provided in bstree.h is missing the implementations for the private inorder and preorder
functions. The coding part of this assignment is to implement these two functions.
When completed, the test program provided should produce the following output:
Values stored in the tree are:
bird
cat
deer
dog
giraffe
groundhog
horse
snake
turtle
The structure of the tree is as follows:
dog
-bird
--cat
---deer
-turtle
--giraffe
---snake
----groundhog
-----horse
Copied!
Written Part
In addition to the coding noted above, give an analysis of all public member functions of the class,
including all constructors, the destructor, and the overload of the assignment operator. For your
analysis you may assume a well-balanced tree (whereas a lopsided tree might lead to a different
analysis).
bstree.h
#pragma once
// A Binary Search Tree implementation.
template <typename T>
class BSTree {
private:
// A node in the tree. Each node has pointers to its left and right nodes
// as well as its parent. When a node is created, the parent and data item
// must be provided.
class node {
public:
T data;
node* left;
node* right;
node* parent;
node (const T& d, node* p) {
parent = p;
data = d;
left = right = nullptr;
}
};
// Pointer to the root node. Initially this is null for an empty tree.
node* root;
// Copy the subtree of another BSTree object into this object. Used by
// the copy constructor and assignment operator.
void copy (node* p) {
if (p) { // If p points to a node...
insert(p->data); // Insert data item
copy(p->left); // Copy the left subtree
copy(p->right); // Copy the right subtree
}
}
// Destroy a node and all nodes in both subtrees. Called by the
// destructor.
void destroy (node* p) {
if (p) { // If p is not null...
destroy(p->left); // Destroy the left subtree
destroy(p->right); // Destroy the right subtree
delete p; // Destroy the node
}
}
// Helper function to determine if a data value is contained in the tree.
// Takes the data value being searched and a pointer to the node in the
// tree. Returns pointer to node in which data item is found, a null
// pointer otherwise.
node* find (const T& .
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
}
/* ...
Thisi s a program of a binary tree which is extended from its super class Simple Tree. It uses all the functionalities from its super class. A binary tree consists of two leaves mainly left child nodes and right child nodes.
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.
Add these three functions to the class binaryTreeType (provided).W.pdfindiaartz
Add these three functions to the class binaryTreeType (provided).
Write the definition of the function, nodeCount, that returns the number of nodes in the binary
tree.
Write the definition of the function, leavesCount, that takes as a parameter a pointer to the root
node of a binary tree and returns the number of leaves in a binary tree.
Write a function, swapSubtrees, that swaps all of the left and right subtrees of a binary tree. Print
the original tree and the resulting tree using a pre-order traversal.
Write a program to test your new functions. Use the data provided to build your binary search
tree (-999 is the sentinel): (C++)
Data: 65 55 22 44 61 19 90 10 78 52 -999
Already completed code is below:
//Header File Binary Search Tree
#ifndef H_binarySearchTree
#define H_binarySearchTree
#include \"binaryTree.h\"
#include
using namespace std;
template
class bSearchTreeType: public binaryTreeType
{
public:
bool search(const elemType& searchItem) const;
//Function to determine if searchItem is in the binary
//search tree.
//Postcondition: Returns true if searchItem is found in
// the binary search tree; otherwise,
// returns false.
void insert(const elemType& insertItem);
//Function to insert insertItem in the binary search tree.
//Postcondition: If there is no node in the binary search
// tree that has the same info as
// insertItem, a node with the info
// insertItem is created and inserted in the
// binary search tree.
void deleteNode(const elemType& deleteItem);
//Function to delete deleteItem from the binary search tree
//Postcondition: If a node with the same info as deleteItem
// is found, it is deleted from the binary
// search tree.
// If the binary tree is empty or deleteItem
// is not in the binary tree, an appropriate
// message is printed.
private:
void deleteFromTree(nodeType* &p);
//Function to delete the node to which p points is
//deleted from the binary search tree.
//Postcondition: The node to which p points is deleted
// from the binary search tree.
};
template
bool bSearchTreeType::search
(const elemType& searchItem) const
{
nodeType *current;
bool found = false;
if (this->root == NULL)
cout << \"Cannot search an empty tree.\" << endl;
else
{
current = this->root;
while (current != NULL && !found)
{
if (current->info == searchItem)
found = true;
else if (current->info > searchItem)
current = current->lLink;
else
current = current->rLink;
}//end while
}//end else
return found;
}//end search
template
void bSearchTreeType::insert
(const elemType& insertItem)
{
nodeType *current; //pointer to traverse the tree
nodeType *trailCurrent; //pointer behind current
nodeType *newNode; //pointer to create the node
newNode = new nodeType;
newNode->info = insertItem;
newNode->lLink = NULL;
newNode->rLink = NULL;
if (this->root == NULL)
this->root = newNode;
else
{
current = this->root;
while (current != NULL)
{
trailCurrent = current;
if (current->info == insertItem)
{
cout << \"The item to be inserted is already \";
cout << \"in the t.
Assg 12 Binary Search Trees COSC 2336assg-12.cppAssg 12 Binary .docxfestockton
Assg 12 Binary Search Trees COSC 2336/assg-12.cppAssg 12 Binary Search Trees COSC 2336/assg-12.cpp/**
* @author Jane Programmer
* @cwid 123 45 678
* @class COSC 2336, Spring 2019
* @ide Visual Studio Community 2017
* @date April 8, 2019
* @assg Assignment 12
*
* @description Assignment 12 Binary Search Trees
*/
#include<cassert>
#include<iostream>
#include"BinaryTree.hpp"
usingnamespace std;
/** main
* The main entry point for this program. Execution of this program
* will begin with this main function.
*
* @param argc The command line argument count which is the number of
* command line arguments provided by user when they started
* the program.
* @param argv The command line arguments, an array of character
* arrays.
*
* @returns An int value indicating program exit status. Usually 0
* is returned to indicate normal exit and a non-zero value
* is returned to indicate an error condition.
*/
int main(int argc,char** argv)
{
// -----------------------------------------------------------------------
cout <<"--------------- testing BinaryTree construction ----------------"<< endl;
BinaryTree t;
cout <<"<constructor> Size of new empty tree: "<< t.size()<< endl;
cout << t << endl;
assert(t.size()==0);
cout << endl;
// -----------------------------------------------------------------------
cout <<"--------------- testing BinaryTree insertion -------------------"<< endl;
//t.insert(10);
//cout << "<insert> Inserted into empty tree, size: " << t.size() << endl;
//cout << t << endl;
//assert(t.size() == 1);
//t.insert(3);
//t.insert(7);
//t.insert(12);
//t.insert(15);
//t.insert(2);
//cout << "<insert> inserted 5 more items, size: " << t.size() << endl;
//cout << t << endl;
//assert(t.size() == 6);
cout << endl;
// -----------------------------------------------------------------------
cout <<"--------------- testing BinaryTree height -------------------"<< endl;
//cout << "<height> Current tree height: " << t.height() << endl;
//assert(t.height() == 3);
// increase height by 2
//t.insert(4);
//t.insert(5);
//cout << "<height> after inserting nodes, height: " << t.height()
// << " size: " << t.size() << endl;
//cout << t << endl;
//assert(t.height() == 5);
//assert(t.size() == 8);
cout << endl;
// -----------------------------------------------------------------------
cout <<"--------------- testing BinaryTree clear -------------------"<< endl;
//t.clear();
//cout << "<clear> after clearing tree, height: " << t.height()
// << " size: " << t.size() << endl;
//cout << t << endl;
//assert(t.size() == 0);
//assert(t.height() == 0);
cout << endl;
// return 0 to indicate successful completion
return0;
}
Assg 12 Binary Search Trees COSC 2336/assg-12.pdf
Assg 12: Binary Search Trees
COSC 2336 Spring 2019
April 10, 2019
Dates:
Due: Sunday April 21, by Midnight
Objectives
� Practice recursive algorithms
� Learn how to construct a binary tree usi ...
A perfect left-sided binary tree is a binary tree where every intern.pdfmichardsonkhaicarr37
A perfect left-sided binary tree is a binary tree where every internal node has two children, and
every left child is a leaf. Write an algorithm, based on DFS or BFS, that takes as input an
undirected graph G, and returns whether or not G is (or can be viewed as) a perfect left-sided
binary tree. Analyze the time complexity of your algorithm.
Solution
bfs(G)
{
list L = empty
tree T = empty
choose a starting vertex x
search(x)
while(L nonempty)
remove edge (v,w) from start of L
if w not yet visited
{
add (v,w) to T
search(w)
}
}
dfs(G)
{
list L = empty
tree T = empty
choose a starting vertex x
search(x)
while(L nonempty)
remove edge (v,w) from end of L
if w not yet visited
{
add (v,w) to T
search(w)
}
}
search(vertex v)
{
visit(v);
for each edge (v,w)
add edge (v,w) to end of L
}
mport java.util.*;
public class BST > implements Iterable
{
public static void main(String[] args)
{
Integer[] a = {1,5,2,7,4};
BST bst = new BST();
for(Integer n : a) bst.insert(n);
bst.preOrderTraversal();
System.out.println();
//testing comparator
//build a mirror BST with a rule: Left > Parent > Right
//code for the comparator at the bottom of the file
bst = new BST(new MyComp1());
for(Integer n : a) bst.insert(n);
bst.preOrderTraversal();
System.out.println();
bst.inOrderTraversal();
System.out.println();
for(Integer n : bst) System.out.print(n);
System.out.println();
System.out.println(bst);
//testing restoring a tree from two given traversals
bst.restore(new Integer[] {11,8,6,4,7,10,19,43,31,29,37,49},
new Integer[] {4,6,7,8,10,11,19,29,31,37,43,49});
bst.preOrderTraversal();
System.out.println();
bst.inOrderTraversal();
System.out.println();
//testing diameter
System.out.println(\"diameter = \" + bst.diameter());
//testing width
System.out.println(\"width = \" + bst.width());
}
private Node root;
private Comparator comparator;
public BST()
{
root = null;
comparator = null;
}
public BST(Comparator comp)
{
root = null;
comparator = comp;
}
private int compare(T x, T y)
{
if(comparator == null) return x.compareTo(y);
else
return comparator.compare(x,y);
}
/*****************************************************
*
* INSERT
*
******************************************************/
public void insert(T data)
{
root = insert(root, data);
}
private Node insert(Node p, T toInsert)
{
if (p == null)
return new Node(toInsert);
if (compare(toInsert, p.data) == 0)
return p;
if (compare(toInsert, p.data) < 0)
p.left = insert(p.left, toInsert);
else
p.right = insert(p.right, toInsert);
return p;
}
/*****************************************************
*
* SEARCH
*
******************************************************/
public boolean search(T toSearch)
{
return search(root, toSearch);
}
private boolean search(Node p, T toSearch)
{
if (p == null)
return false;
else
if (compare(toSearch, p.data) == 0)
return true;
else
if (compare(toSearch, p.data) < 0)
return search(p.left, toSearch);
else
return search(p.right, toSearch);
}
/*****************************************************.
MAINCPP include ltiostreamgt include ltstringgt u.pdfadityastores21
MAIN.CPP
#include <iostream>
#include <string>
using namespace std;
#include "bstree.h"
// Prints a single string, used by FSTree::inorder to print all
// values in the tree in correct order.
void print_string (string s) { cout << s << endl; }
// Prints a single string preceeded by a number of hyphens, used by
// BSTree::preorder to print a visual representation of the tree.
void print_string_depth (string s, int n) {
for (int i = 0; i < n; i++)
cout << '-';
cout << s << endl;
}
int main () {
// Create a binary search tree.
BSTree<string> t;
// Insert some strings for testing.
t.insert("dog");
t.insert("bird");
t.insert("cat");
t.insert("turtle");
t.insert("giraffe");
t.insert("snake");
t.insert("deer");
t.insert("groundhog");
t.insert("horse");
// Output the values stored in the tree.
cout << "Values stored in the tree are:n";
t.inorder(print_string);
cout << "n";
cout << "The structure of the tree is as follows:n";
t.preorder(print_string_depth);
cout << "n";
}
BSTREE.h
#pragma once
// A Binary Search Tree implementation.
template <typename T>
class BSTree {
private:
// A node in the tree. Each node has pointers to its left and right nodes
// as well as its parent. When a node is created, the parent and data item
// must be provided.
class node {
public:
T data;
node* left;
node* right;
node* parent;
node (const T& d, node* p) {
parent = p;
data = d;
left = right = nullptr;
}
};
// Pointer to the root node. Initially this is null for an empty tree.
node* root;
// Copy the subtree of another BSTree object into this object. Used by
// the copy constructor and assignment operator.
void copy (node* p) {
if (p) { // If p points to a node...
insert(p->data); // Insert data item
copy(p->left); // Copy the left subtree
copy(p->right); // Copy the right subtree
}
}
// Destroy a node and all nodes in both subtrees. Called by the
// destructor.
void destroy (node* p) {
if (p) { // If p is not null...
destroy(p->left); // Destroy the left subtree
destroy(p->right); // Destroy the right subtree
delete p; // Destroy the node
}
}
// Helper function to determine if a data value is contained in the tree.
// Takes the data value being searched and a pointer to the node in the
// tree. Returns pointer to node in which data item is found, a null
// pointer otherwise.
node* find (const T& d, node* p) const {
// Given: p is a pointer to an existing node
if (d == p->data) // Is this the value we're looking for?
return p;
if (d < p->data) // Check left side, if null then not found
return p->left ? find(d, p->left) : nullptr;
return p->right ? find(d, p->right) : nullptr; // Check right side...
}
// Helper function to insert a data item into the tree. Takes the data
// and a pointer to a node in the tree. Recursively decends down the tree
// until position were insertion should take place is found.
void insert (const T& d, node* p) {
// Given: p is a pointer to an existing node (root of a subtree)
if (d < p->data) { // Insert into left subtree?
if (p->left) // Left.
(1)Objective Binary Search Tree traversal (2 points)Use traversal.pdfarihantmobileselepun
(1)Objective: Binary Search Tree traversal (2 points)
Use traversal.pptx as guidance to write a program to build a binary search tree Dictionary. I of
BST have the same data from each input record.
Download traversal-lab.pptx, inventory.txt, BinNode.java, BSTNode.java, BST.java,
Dictionary.java .
Perform specifications as follow:
(a)Provide Add, Delete and Retrieve functions for user to access the database. Reject duplicate
record when add a new record.
(b)Modify BST.java to add printpostOrder, printpreOrder methods.
(c)At the end, display inorder, postorder and preorder of the tree.
Codes:
/** Source code example for \"A Practical Introduction to Data
Structures and Algorithm Analysis, 3rd Edition (Java)\"
by Clifford A. Shaffer
Copyright 2008-2011 by Clifford A. Shaffer
*/
/** ADT for binary tree nodes */
public interface BinNode {
/** Get and set the element value */
public E element();
public void setElement(E v);
/** @return The left child */
public BinNode left();
/** @return The right child */
public BinNode right();
/** @return True if a leaf node, false otherwise */
public boolean isLeaf();
}
//********************************************************************
// StringTree.java
//
//********************************************************************
import java.util.*;
public class StringTree
{
private Node root;
//----------------------------------------------------------------
// Creates an initially empty tree.
//----------------------------------------------------------------
public StringTree()
{
root = null;
}
//----------------------------------------------------------------
// Adds a string to the tree.
//----------------------------------------------------------------
public void addString (String str)
{
root = addStringToSubTree(str, root);
}
//----------------------------------------------------------------
// Adds a string to the subtree with the given root node
//----------------------------------------------------------------
private Node addStringToSubTree (String str, Node node)
{
Node result = node;
if (node == null)
result = new Node(str);
// If the new string comes before the string in the node, add
// the new string to the left child. Otherwise, add it to the
// right child.
else
if (str.compareTo(node.value) < 0)
node.left = addStringToSubTree(str, node.left);
else
node.right = addStringToSubTree(str, node.right);
return result;
}
//----------------------------------------------------------------
// Prints the result of a depth-first traversal of the tree using
// recursion.
//----------------------------------------------------------------
public void traverseWithRecursion()
{
traverseWithRecursion(root);
}
//----------------------------------------------------------------
// Prints the elements in the specified tree using recursion.
//----------------------------------------------------------------
private void traverseWithRecursion (Node node)
{
if (node != null)
{
traverseWithRecursion (node.left);
System.
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
.
For the code below complete the preOrder() method so that it perform.pdfxlynettalampleyxc
For the code below complete the preOrder() method so that it performs a preOrder traversal of
the tree. For each node it traverses, it should call sb.append() to add a \"[\" the results of
traversing the subtree rooted at that node, and then a \"]\". You should add a space before the
results of the left and right child traversals, but only if the node exists.
code:
Solution
In preorder Nodes visited are in the order of
code:
package edu.buffalo.cse116;
import java.util.AbstractSet;
import java.util.Iterator;
public class BinarySearchTree> extends AbstractSet {
protected Entry root;
protected int size;
/**
* Initializes this BinarySearchTree object to be empty, to contain only
* elements of type E, to be ordered by the Comparable interface, and to
* contain no duplicate elements.
*/
public BinarySearchTree() {
root = null;
size = 0;
}
/**
* Initializes this BinarySearchTree object to contain a shallow copy of a
* specified BinarySearchTree object. The worstTime(n) is O(n), where n is the
* number of elements in the specified BinarySearchTree object.
*
* @param otherTree - the specified BinarySearchTree object that this
* BinarySearchTree object will be assigned a shallow copy of.
*/
public BinarySearchTree(BinarySearchTree otherTree) {
root = copy(otherTree.root, null);
size = otherTree.size;
}
/* Method to complete is here! */
public void preOrder(Entry ent, StringBuilder sb) {
preorder(root)
protected Entry copy(Entry p, Entry parent) {
if (p != null) {
Entry q = new Entry(p.element, parent);
q.left = copy(p.left, q);
q.right = copy(p.right, q);
return q;
}
return null;
} // method copy
@SuppressWarnings(\"unchecked\")
@Override
public boolean equals(Object obj) {
if (!(obj instanceof BinarySearchTree)) {
return false;
}
return equals(root, ((BinarySearchTree) obj).root);
}
public boolean equals(Entry p, Entry q) {
if ((p == null) || (q == null)) {
return p == q;
}
if (!p.element.equals(q.element)) {
return false;
}
if (equals(p.left, q.left) && equals(p.right, q.right)) {
return true;
}
return false;
}
/**
* Returns the size of this BinarySearchTree object.
*
* @return the size of this BinarySearchTree object.
*/
@Override
public int size() {
return size;
}
/**
* Iterator method will be implemented for a future
*
* @return an iterator positioned at the smallest element in this
* BinarySearchTree object.
*/
@Override
public Iterator iterator() {
throw new UnsupportedOperationException(\"Not implemented yet!\");
}
/**
* Determines if there is at least one element in this BinarySearchTree object
* that equals a specified element. The worstTime(n) is O(n) and
* averageTime(n) is O(log n).
*
* @param obj - the element sought in this BinarySearchTree object.
* @return true - if there is an element in this BinarySearchTree object that
* equals obj; otherwise, return false.
* @throws ClassCastException - if obj cannot be compared to the elements in
* this BinarySearchTree object.
* @throws NullPointerException - if obj is null.
*/
@Override
public .
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.
On the code which has a class in which I implementing a binary tree .pdfwasemanivytreenrco51
On the code which has a class in which I implementing a binary tree using an array. This array,
named store, stores Node in entries corresponding to
nodes in the tree and null if the node does not exist. Complete the countLeavesmethod so that it
returns the number of leaves in this tree.
Code:
Solution
import java.util.AbstractSet; import java.util.Arrays; import java.util.Iterator; import
java.util.NoSuchElementException; /** * Implementation of an abstract set using an array-
based binary tree. This is * used to help teach binary tree\'s and will have more details explained
in * future lectures. * * @author William J. Collins * @author Matthew Hertz * @param
Data type (which must be Comparable) of the elements in this tree. */ public class
ArrayBinaryTree> extends AbstractSet { /** Entry in the data store where the root node can be
found. */ private static final int ROOT = 0; /** Array used to store the nodes which consist of
this binary tree. */ protected Node[] store; /** Number of elements within the tree. */
protected int size; /** * Initializes this ArrayBinaryTree object to be empty. This creates the
array * in which items will be stored. */ @SuppressWarnings(\"unchecked\") public
ArrayBinaryTree() { store = new Node[63]; size = 0; } /** * Initializes this
ArrayBinaryTree object to contain a shallow copy of a * specified ArrayBinaryTree object.
The worstTime(n) is O(n), where n is the * number of elements in the specified
ArrayBinaryTree object. * * @param otherTree The tree which will be copied to create our
new tree, */ @SuppressWarnings(\"unchecked\") public ArrayBinaryTree(ArrayBinaryTree
otherTree) { store = (Node[]) Arrays.copyOf(otherTree.store, otherTree.store.length); size =
otherTree.size; } public int countLeaves() { } /** * Returns the size of this
ArrayBinaryTree object. * * @return the size of this ArrayBinaryTree object. */
@Override public int size() { return size; } /** * Returns an iterator that will return the
elements in this ArrayBinaryTree, * but without any specific ordering. * * @return Iterator
positioned at the smallest element in this ArrayBinaryTree * object. */ @Override
public Iterator iterator() { return new ArrayTreeIterator(); } /** * Determines if there is at
least one element in this ArrayBinaryTree object * that equals a specified element. The
worstTime(n) is O(n) and * averageTime(n) is O(log n). * * @param obj - the element
sought in this ArrayBinaryTree object. * @return true - if there is an element in this
ArrayBinaryTree object that * equals obj; otherwise, return false. * @throws
ClassCastException - if obj cannot be compared to the elements in * this
ArrayBinaryTree object. * @throws NullPointerException - if obj is null. */ @Override
public boolean contains(Object obj) { return getEntry(obj) != null; } /** * Ensures that
this ArrayBinaryTree object contains a specified element. The * worstTime(n) is O(n) for this
addition. * * @param element Element we want to be certain is contained within.
Objective Binary Search Tree traversal (2 points)Use traversal.pp.pdfsivakumar19831
Objective: Binary Search Tree traversal (2 points)
Use traversal.pptx as guidance to write a program to build a binary search tree Dictionary. Input
records from inventory.txt. Both key and Element of BST have the same data from each input
record.
public interface BinNode {
/** Get and set the element value */
public E element();
public void setElement(E v);
/** @return The left child */
public BinNode left();
/** @return The right child */
public BinNode right();
/** @return True if a leaf node, false otherwise */
public boolean isLeaf();
}
import java.lang.Comparable;
/** Binary Search Tree implementation for Dictionary ADT */
class BST, E>
implements Dictionary {
private BSTNode root; // Root of the BST
int nodecount; // Number of nodes in the BST
/** Constructor */
BST() { root = null; nodecount = 0; }
/** Reinitialize tree */
public void clear() { root = null; nodecount = 0; }
/** Insert a record into the tree.
@param k Key value of the record.
@param e The record to insert. */
public void insert(Key k, E e) {
root = inserthelp(root, k, e);
nodecount++;
}
// Return root
public BSTNode getRoot()
{
return root;
}
/** Remove a record from the tree.
@param k Key value of record to remove.
@return The record removed, null if there is none. */
public E remove(Key k) {
E temp = findhelp(root, k); // First find it
if (temp != null) {
root = removehelp(root, k); // Now remove it
nodecount--;
}
return temp;
}
/** Remove and return the root node from the dictionary.
@return The record removed, null if tree is empty. */
public E removeAny() {
if (root == null) return null;
E temp = root.element();
root = removehelp(root, root.key());
nodecount--;
return temp;
}
/** @return Record with key value k, null if none exist.
@param k The key value to find. */
public E find(Key k) { return findhelp(root, k); }
/** @return The number of records in the dictionary. */
public int size() { return nodecount; }
private E findhelp(BSTNode rt, Key k) {
if (rt == null) return null;
if (rt.key().compareTo(k) > 0)
return findhelp(rt.left(), k);
else if (rt.key().compareTo(k) == 0) return rt.element();
else return findhelp(rt.right(), k);
}
/** @return The current subtree, modified to contain
the new item */
private BSTNode inserthelp(BSTNode rt,
Key k, E e) {
if (rt == null) return new BSTNode(k, e);
if (rt.key().compareTo(k) > 0)
rt.setLeft(inserthelp(rt.left(), k, e));
else
rt.setRight(inserthelp(rt.right(), k, e));
return rt;
}
/** Remove a node with key value k
@return The tree with the node removed */
private BSTNode removehelp(BSTNode rt,Key k) {
if (rt == null) return null;
if (rt.key().compareTo(k) > 0)
rt.setLeft(removehelp(rt.left(), k));
else if (rt.key().compareTo(k) < 0)
rt.setRight(removehelp(rt.right(), k));
else { // Found it
if (rt.left() == null) return rt.right();
else if (rt.right() == null) return rt.left();
else { // Two children
BSTNode temp = getmin(rt.right());
rt.setElement(temp.element());
rt.setKey(temp.key());
rt.setRight(deletemin(rt.right(.
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.
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.
A)B) C++ program to create a Complete Binary tree from its Lin.pdfanton291
A)
B)
// C++ program to create a Complete Binary tree from its Linked List
// Representation
#include
#include
#include
using namespace std;
// Linked list node
struct ListNode
{
int data;
ListNode* next;
};
// Binary tree node structure
struct BinaryTreeNode
{
int data;
BinaryTreeNode *left, *right;
};
// Function to insert a node at the beginning of the Linked List
void push(struct ListNode** head_ref, int new_data)
{
// allocate node and assign data
struct ListNode* new_node = new ListNode;
new_node->data = new_data;
// link the old list off the new node
new_node->next = (*head_ref);
// move the head to point to the new node
(*head_ref) = new_node;
}
// method to create a new binary tree node from the given data
BinaryTreeNode* newBinaryTreeNode(int data)
{
BinaryTreeNode *temp = new BinaryTreeNode;
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
// converts a given linked list representing a complete binary tree into the
// linked representation of binary tree.
void convertList2Binary(ListNode *head, BinaryTreeNode* &root)
{
// queue to store the parent nodes
queue q;
// Base Case
if (head == NULL)
{
root = NULL; // Note that root is passed by reference
return;
}
// 1.) The first node is always the root node, and add it to the queue
root = newBinaryTreeNode(head->data);
q.push(root);
// advance the pointer to the next node
head = head->next;
// until the end of linked list is reached, do the following steps
while (head)
{
// 2.a) take the parent node from the q and remove it from q
BinaryTreeNode* parent = q.front();
q.pop();
// 2.c) take next two nodes from the linked list. We will add
// them as children of the current parent node in step 2.b. Push them
// into the queue so that they will be parents to the future nodes
BinaryTreeNode *leftChild = NULL, *rightChild = NULL;
leftChild = newBinaryTreeNode(head->data);
q.push(leftChild);
head = head->next;
if (head)
{
rightChild = newBinaryTreeNode(head->data);
q.push(rightChild);
head = head->next;
}
// 2.b) assign the left and right children of parent
parent->left = leftChild;
parent->right = rightChild;
}
}
// Utility function to traverse the binary tree after conversion
void inorderTraversal(BinaryTreeNode* root)
{
if (root)
{
inorderTraversal( root->left );
cout << root->data << \" \";
inorderTraversal( root->right );
}
}
// Driver program to test above functions
int main()
{
// create a linked list shown in above diagram
struct ListNode* head = NULL;
push(&head, 36); /* Last node of Linked List */
push(&head, 30);
push(&head, 25);
push(&head, 15);
push(&head, 12);
push(&head, 10); /* First node of Linked List */
BinaryTreeNode *root;
convertList2Binary(head, root);
cout << \"Inorder Traversal of the constructed Binary Tree is: \ \";
inorderTraversal(root);
return 0;
}
c)
#include
#include
using namespace std;
template
class bintree
{
bintree *left;
T data;
bintree *right;
public :
bintree()
{
left=right=NULL;
}
void create();
void preorder();
void inorder();
void pos.
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;
}.
ReversePoem.java ---------------------------------- public cl.pdfravikapoorindia
ReversePoem.java :-
---------------------------------
public class ReversePoem {
/*This programs has you display a pessimistic poem from a list of phrases*/
// and then reverse the phrases to find another more optimistic poem.
public static void main(String[] args) throws Exception
{
//Queue object
MyQueue queue = new MyQueue<>();
//Stack object
MyStack stack = new MyStack<>();
//String buffer to apppend all Strings
StringBuffer sb = new StringBuffer();
// Create a single String object from the 16 Strings below
String set1 = \"I am part of a lost generation#and I refuse to believe that#\";
sb.append(set1);
String set2 = \"I can change the world#I realize this may be a shock but#\";
sb.append(set2);
String set3 = \"\'Happiness comes from within\'#is a lie, and#\";
sb.append(set3);
String set4 = \"\'Money will make me happy\'#So in 30 years I will tell my children#\";
sb.append(set4);
String set5 = \"they are not the most important thing in my life#\";
sb.append(set5);
String set6 = \"My employer will know that#I have my priorities straight because#\";
sb.append(set6);
String set7 = \"work#is more important than#family#I tell you this#\";
sb.append(set7);
String set8 = \"Once upon a time#Families stayed together#\";
sb.append(set8);
String set9 = \"but this will not be true in my era#\";
sb.append(set9);
String set10 = \"This is a quick fix society#Experts tell me#\";
sb.append(set10);
String set11 = \"30 years from now, I will be celebrating the 10th anniversary of my
divorce#\";
sb.append(set11);
String set12 = \"I do not concede that#I will live in a country of my own making#\";
sb.append(set12);
String set13 = \"In the future#Environmental destruction will be the norm#\";
sb.append(set13);
String set14 = \"No longer can it be said that#My peers and I care about this earth#\";
sb.append(set14);
String set15 = \"It will be evident that#My generation is apathetic and lethargic#\";
sb.append(set15);
String set16 = \"It is foolish to presume that#There is hope#\";
sb.append(set16);
String finalString = sb.toString();
String itmes[] = finalString.split(\"#\");
System.out.println(\"========== Original Phrase ==============\");
for(int i = 0 ; i < itmes.length;i++){
queue.enqueue(itmes[i]);
System.out.println(itmes[i]);
}
for(int i = 0 ; i < itmes.length;i++){
stack.push(queue.dequeue());
}
System.out.println(\"========== Reverse Phrase ==============\");
for(int i = 0 ; i < itmes.length;i++){
System.out.println(stack.pop());
}
/* You are given a list of phrases in Strings; the phrases
are separated by pound signs: \'#\':
1. Create a single String object from this list.
2. Then, split the String of phrases into an array of
phrases using the String split method.
3. Display a poem by walking through the array and
displaying each phrase one per line.
4. And, at the same time, place each phrase on a
MyQueue object using only the enqueue method.
5. After all the phrases have been placed on the queue,
transfer the phrases from the MyQueue object to a
MyS.
Create an implementation of a binary tree using the recursive appr.pdffederaleyecare
\"Create an implementation of a binary tree using the recursive approach introduced in the
chapter. In this approach, each node is a binary tree. Thus a binary tree contains a reference to
the element stored at its root as well as references to its left and right subtrees. You may also
want to include a reference to its parent.\" p.741
You need to use the locally implemented binary tree. This means you need to have a \"jsjf\"
subfolder with at least these files: BinaryTreeADT.java, LinkedBinaryTree.java,
BinaryTreeNode.java, and the exceptions sub-subfolder.
Test/demonstrate your binary tree by doing the following:
Request file name from user,
Read an infix expression from file,
Build binary expression tree,
Display binary expression tree,
Evaluate binary expression tree,
Display result.
##############################################
Note a typical input file can be found here
##############################################
# Version 0.2, fully parenthesized.
# This is a comment
((9 + 4) * 5) + (4 - (6 + 3))
# Note first expression should evaluate to 60
((42 + ( 10 - 2 )) + ( 5 * 3 )) / 6
# Note second expression should evaluate to 65 / 6 or 10 (integer division)
##############################################
My program is below but the out put is incorrect
##############################################
StringTree.java
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Stack;
import jsjf.BinaryTreeNode;
import jsjf.LinkedBinaryTree;
public class StringTree extends LinkedBinaryTree {
public StringTree(String rootStr, StringTree leftSubtree, StringTree rightSubtree) {
root = new BinaryTreeNode(rootStr, leftSubtree, rightSubtree);
} // StringTree
public StringTree(File f) {
Stack leftStack = new Stack(), rightStack = new Stack();
// stacks of left and right subtrees of nodes
Scanner scan;
// scanner for reading from the file
String nodeType,
nodeStr;
// string contained in the current node
boolean hasLeftChild, hasRightChild;
// true if the current node has a left or right child
StringTree leftSubtree, rightSubtree,
// left and right subtrees of the current node
subtree;
// subtree having the current node as its root
// Create a scanner for reading from the file.
try {
scan = new Scanner(f);
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
root = null;
System.out.println(\"\ \"+\"The program has terminated......\");
System.exit(0);
return;
}
// Read the file and build a tree from the bottom up.
while (scan.hasNext()) {
// Input information about a tree node.
nodeType = scan.next();
hasLeftChild = (scan.next().equalsIgnoreCase(\"y\"));
hasRightChild = (scan.next().equalsIgnoreCase(\"y\"));
nodeStr = scan.next();
// Determine the left and right subtrees of the subtree
// having the node as its root.
if (hasLeftChild)
leftSubtree = leftStack.pop();
else
leftSubtree = null;
if (hasRightChild)
rightSubtree = rightStack.pop();
else
rightSubtree = null;
.
Data Structures in C++I am really new to C++, so links are really .pdfrohit219406
Data Structures in C++
I am really new to C++, so links are really hard topic for me. It would be nice if you can provide
explanations of what doubly linked lists are and of some of you steps... Thank you
In this assignment, you will implement a doubly-linked list class, together with some list
operations. To make things easier, you’ll implement a list of int, rather than a template class.
Solution
A variable helps us to identify the data. For ex: int a = 5; Here 5 is identified through variable a.
Now, if we have collection of integers, we need some representation to identify them. We call it
array. For ex: int arr[5]
This array is nothing but a Data Structure.
So, a Data Structure is a way to group the data.
There are many Data Structures available like Arrays, Linked List, Doubly-Linked list, Stack,
Queue, etc.
Doubly-Linked list are the ones where you can traverse from the current node both in left and
right directions.
Why so many different types of Data Structures are required ?
Answer is very simple, grouping of data, storage of data and accessing the data is different.
For example, in case of Arrays we store all the data in contiguous locations.
What if we are not able to store the data in contiguous locations because we have huge data.
Answer is go for Linked List/Doubly-Linked list.
Here we can store the data anywhere and link the data through pointers.
I will try to provide comments for the code you have given. May be this can help you.
#pragma once
/*
dlist.h
Doubly-linked lists of ints
*/
#include
class dlist {
public:
dlist() { }
// Here we are creating a NODE, it has a integer value and two pointers.
// One pointer is to move to next node and other to go back to previous node.
struct node {
int value;
node* next;
node* prev;
};
// To return head pointer, i.e. start of the Doubly-Linked list.
node* head() const { return _head; }
// To return Tail pointer, i.e. end of the Doubly-Linked list.
node* tail() const { return _tail; }
// **** Implement ALL the following methods ****
// Returns the node at a particular index (0 is the head).
node* at(int index){
int cnt = 0;
struct node* tmp = head();
while(tmp!=NULL)
{
if (cnt+1 == index)
return tmp;
tmp = tmp->next;
}
}
// Insert a new value, after an existing one
void insert(node *previous, int value){
// check if the given previous is NULL
if (previous == NULL)
{
printf(\"the given previous node cannot be NULL\");
return;
}
// allocate new node
struct node* new_node =(struct node*) malloc(sizeof(struct node));
// put in the data
new_node->data = new_data;
// Make next of new node as next of previous
new_node->next = previous->next;
// Make the next of previous as new_node
previous->next = new_node;
// Make previous as previous of new_node
new_node->prev = previous;
// Change previous of new_node\'s next node
if (new_node->next != NULL)
new_node->next->prev = new_node;
}
// Delete the given node
void del(node* which){
struct node* head_ref = head();
/* base case */
if(*head_ref == NUL.
Write a program that accepts an arithmetic expression of unsigned in.pdfJUSTSTYLISH3B2MOHALI
Write a program that accepts an arithmetic expression of unsigned integers in postfix notation
and builds the arithmetic expression tree that represents that expression. From that tree, the
corresponding fully parenthesized infix expression should be displayed and a file should be
generated that contains the three address format instructions. This topic is discussed in the week
4 reading in module 2, section II-B. The main class should create the GUI shown below:
Pressing the Construct Tree button should cause the tree to be constructed and using that tree, the
corresponding infix expression should be displayed and the three address instruction file should
be generated. The postfix expression input should not be required to have spaces between every
token. Note in the above example that 9+- are not separated by spaces. The above example
should produce the following output file containing the three address instructions:
Add R0 5 9
Sub R1 3
R0 Mul R2 2 3
Div R3 R1 R2
Inheritance should be used to define the arithmetic expression tree. At a minimum, it should
involve three classes: an abstract class for the tree nodes and two derived classes, one for
operand nodes and another for operator nodes. Other classes should be included as needed to
accomplish good object-oriented design. All instance data must be declared as private.
You may assume that the expression is syntactically correct with regard to the order of operators
and operands, but you should check for invalid tokens, such as characters that are not valid
operators or operands such as 2a, which are not valid integers. If an invalid token is detected a
RuntimeException should be thrown and caught by the main class and an appropriate error
message should be displayed. Three Adddress Generator Enter Postfix Expression 359 2 3
Construct Tree Infix Expression ((3-(5 9))/ (2* 3
Solution
#include
#include
#include
#include
#include
struct TREE //Structure to represent a tree
{
char data;
struct TREE *right,*left,*root;
};
typedef TREE tree; /* Stack Using Linked List */
struct Stack //Structure to represent Stack
{
struct TREE *data;
struct Stack *next,*head,*top; //Pointers to next node,head and top
};
typedef struct Stack node;
node *Nw; //Global Variable to represent node
void initialize(node *&n)
{
n = new node;
n -> next = n -> head = n -> top = NULL;
}
void create(node *n)
{
Nw = new node; //Create a new node
Nw -> next = NULL; //Initialize next pointer field
if(n -> head == NULL) //if first node
{
n -> head = Nw; //Initialize head
n -> top = Nw; //Update top
}
}
void push(node *n,tree *ITEM)
{
node *temp = n -> head;
if(n -> head == NULL) //if First Item is Pushed to Stack
{
create(n); //Create a Node
n -> head -> data = ITEM; //Insert Item to head of List
n -> head = Nw;
return; //Exit from Function
}
create(n); //Create a new Node
Nw -> data = ITEM; //Insert Item
while(temp -> next != NULL)
temp = temp -> next; //Go to Last Node
temp -> next = Nw; //Point New node
n -> top = Nw; //Upda.
Assignment 9 (Parent reference for BST) Redefine TreeNode by adding .pdfFootageetoffe16
Assignment 9 (Parent reference for BST) Redefine TreeNode by adding a reference to a node’s
parent, as shown below:
BST.TreeNode
#element
#left : TreeNode
#right: TreeNode
#parent: TreeNode
Implement the insert and delete methods in BST class to update the parent for each node in the
tree.
Add the following new method in BST:
/** Return the node for the specific element.
* Return null if the element is not in the tree. */
private TreeNode getNode(E element)
/** Returns true if the node for the element is a lead */
private boolean isLeaf(E element)
/** Returns the path of the element from the specific element to the root in an array list */
public ArrayList getPath(E e)
Write a test program that prompts the user to enter 10 integers, adds them to the tree, deletes the
first integer from the tree, and displays the paths for all leaf nodes.
Sample run
Enter 10 integers :
45 54 67 56 50 45 23 59 23 67
[50, 54, 23]
[59, 56, 67, 54, 23]
Solution
import java.util.NoSuchElementException; public class TreeSet> implements Set {
private TreeNode root; private int size; // Constructs an empty set. public
TreeSet() { root = null; size = 0; } // Adds the given value to this
set, if it was not already in the set. // If the element is already a member of this set, adding it
again has no effect. public void add(E value) { root = add(root, value); }
// private recursive helper for add // uses the \"x = change(x)\" pattern: // pass in
current state of root // return out desired new state of root private TreeNode
add(TreeNode node, E value) { if (node == null) { node = new
TreeNode(value); // reached dead end; put new node here size++; }
else if (value.compareTo(node.data) > 0) { node.right = add(node.right, value);
} else if (value.compareTo(node.data) < 0) { node.left = add(node.left,
value); } // else a duplicate; do nothing return node; } // Returns
true if this set contains the given element value. public boolean contains(E value) {
return contains(root, value); } // private recursive helper for contains private
boolean contains(TreeNode node, E value) { if (node == null) { return
false; } else if (value.compareTo(node.data) > 0) { return
contains(node.right, value); } else if (value.compareTo(node.data) < 0) {
return contains(node.left, value); } else { // value.equals(root.data);
found it! return true; } } // Returns the minimum value in this
set. // Throws a NoSuchElementException if this set is empty. public E getMin() {
if (root == null) { throw new NoSuchElementException(\"empty tree\");
} return getMin(root); } // private recursive helper for getMin
private E getMin(TreeNode node) { if (node.left == null) { return
node.data; } else { return getMin(node.left); } }
// Returns true if this set does not contain any elements. public boolean isEmpty() {
return size == 0; } // Prints all elements of this tree in a left-to-right order (in-order)
traversal. public void print() { print(root); } // private recursive helper
for print private void print(TreeNode .
5. Design and implement a method contains 2 for BinarySearchTree, fu.pdframbagra74
5. Design and implement a method contains 2 for BinarySearchTree, functionall equivalent to
the contains method, that does not use recursion.
show the driver code and do this in java
this is the binarysearchtree
import java.util.*; // Iterator, Comparator
public class BinarySearchTree implements BSTInterface
{
protected BSTNode root; // reference to the root of this BST
protected Comparator comp; // used for all comparisons
protected boolean found; // used by remove
public BinarySearchTree()
// Precondition: T implements Comparable
// Creates an empty BST object - uses the natural order of elements.
{
root = null;
comp = new Comparator()
{
public int compare(T element1, T element2)
{
return ((Comparable)element1).compareTo(element2);
}
};
}
public BinarySearchTree(Comparator comp)
// Creates an empty BST object - uses Comparator comp for order
// of elements.
{
root = null;
this.comp = comp;
}
public boolean isFull()
// Returns false; this link-based BST is never full.
{
return false;
}
public boolean isEmpty()
// Returns true if this BST is empty; otherwise, returns false.
{
return (root == null);
}
public T min()
// If this BST is empty, returns null;
// otherwise returns the smallest element of the tree.
{
if (isEmpty())
return null;
else
{
BSTNode node = root;
while (node.getLeft() != null)
node = node.getLeft();
return node.getInfo();
}
}
public T max()
// If this BST is empty, returns null;
// otherwise returns the largest element of the tree.
{
if (isEmpty())
return null;
else
{
BSTNode node = root;
while (node.getRight() != null)
node = node.getRight();
return node.getInfo();
}
}
private int recSize(BSTNode node)
// Returns the number of elements in subtree rooted at node.
{
if (node == null)
return 0;
else
return 1 + recSize(node.getLeft()) + recSize(node.getRight());
}
public int size()
// Returns the number of elements in this BST.
{
return recSize(root);
}
public int size2()
// Returns the number of elements in this BST.
{
int count = 0;
if (root != null)
{
LinkedStack> nodeStack = new LinkedStack>();
BSTNode currNode;
nodeStack.push(root);
while (!nodeStack.isEmpty())
{
currNode = nodeStack.top();
nodeStack.pop();
count++;
if (currNode.getLeft() != null)
nodeStack.push(currNode.getLeft());
if (currNode.getRight() != null)
nodeStack.push(currNode.getRight());
}
}
return count;
}
private boolean recContains(T target, BSTNode node)
// Returns true if the subtree rooted at node contains info i such that
// comp.compare(target, i) == 0; otherwise, returns false.
{
if (node == null)
return false; // target is not found
else if (comp.compare(target, node.getInfo()) < 0)
return recContains(target, node.getLeft()); // Search left subtree
else if (comp.compare(target, node.getInfo()) > 0)
return recContains(target, node.getRight()); // Search right subtree
else
return true; // target is found
}
public boolean contains (T target)
// Returns true if this BST contains a node with info i such that
// comp.compare(target, i) == 0; otherwise, re.
PARTICIPANTS PROFILE ANSWER ABOVE MENTIONED QUESTIONS BY TAKING CARE.docxfarrahkur54
PARTICIPANTS PROFILE
ANSWER ABOVE MENTIONED QUESTIONS BY TAKING CAREGIVERS OF ADULTS IN LONG TERM FACILITY AS AUDIENCE
TRAINING FOR [ PRESSURE ULCER ]
PLEASE PROVIDE CITATIONS AND REFERENCES - VERYIMPORTANT
.
Part3- Offline traffic monitoring In this part will use a PCAP file to.docxfarrahkur54
Part3: Offline traffic monitoring In this part will use a PCAP file to examine the network traffic (offline traffic monitoring) using three IDS tools - Snort - Suricata - Zeek The PCAP file with the name part3.pcap (attached with the project files) containing a captured network traffic for some company having a web site and 256 addresses in the range (192.168.6.0 - 192.168.6.255). The IP address for the network gateway (edge router) is ( 192.168.6.1 ) . The captured network traffic is for some period of time when an attacker started to perform intrusion against the company network. The suspicious address is 192.168.5.55, which conducted a multi-stage attack starting with reconnaissance. A kill chain representing multi-stage attack is a systematic process to target and engage an attacker to perform the desired attack. The following steps are the typical stages followed by any professional attacker. 1. Reconnaissance - Research, identification and selection of targets, often represented as crawling Internet websites such as conference proceedings and mailing lists for email addresses, social relationships, or information on specific technologies. 2. Weaponization - Coupling a remote access trojan with an exploit into a deliverable payload, typically by means of an automated tool (weaponizer). Increasingly, client application data files such as Adobe Portable Document Format (PDF) or Microsoft Office documents serve as the weaponized deliverable. 3. Delivery - Transmission of the weapon to the targeted environment. The three most prevalent delivery vectors for weaponized payloads by APT actors, as observed by the Lockheed Martin Computer Incident Response Team (LM-CIRT) for the years 2004-2010, are email attachments, websites, and USB removable media. 4. Exploitation - After the weapon is delivered to victim host, exploitation triggers intruders' code. Most often, exploitation targets an application or operating system vulnerability, but it could also more simply exploit the users themselves or leverage an operating system feature that auto-executes code. 5. Installation - Installation of a remote access trojan or backdoor on the victim system allows the adversary to maintain persistence inside the environment. 6. Command and Control (C2) - Typically, compromised hosts must beacon outbound to an Internet controller server to establish a C2 channel. APT malware especially requires manual interaction rather than conduct activity automatically. Once the C 2 channel establishes, intruders have "hands on the keyboard" access inside the target environment. 7. Actions on Objectives - Only now, after progressing through the first six phases, can intruders take actions to achieve their original objectives. Typically, this objective is data exfiltration which involves collecting, encrypting and extracting information from the victim environment; violations of data integrity or availability are potential objectives as well. Alternatively, the intruders may.
More Related Content
Similar to Once you have all the structures working as intended- it is time to co.docx
A perfect left-sided binary tree is a binary tree where every intern.pdfmichardsonkhaicarr37
A perfect left-sided binary tree is a binary tree where every internal node has two children, and
every left child is a leaf. Write an algorithm, based on DFS or BFS, that takes as input an
undirected graph G, and returns whether or not G is (or can be viewed as) a perfect left-sided
binary tree. Analyze the time complexity of your algorithm.
Solution
bfs(G)
{
list L = empty
tree T = empty
choose a starting vertex x
search(x)
while(L nonempty)
remove edge (v,w) from start of L
if w not yet visited
{
add (v,w) to T
search(w)
}
}
dfs(G)
{
list L = empty
tree T = empty
choose a starting vertex x
search(x)
while(L nonempty)
remove edge (v,w) from end of L
if w not yet visited
{
add (v,w) to T
search(w)
}
}
search(vertex v)
{
visit(v);
for each edge (v,w)
add edge (v,w) to end of L
}
mport java.util.*;
public class BST > implements Iterable
{
public static void main(String[] args)
{
Integer[] a = {1,5,2,7,4};
BST bst = new BST();
for(Integer n : a) bst.insert(n);
bst.preOrderTraversal();
System.out.println();
//testing comparator
//build a mirror BST with a rule: Left > Parent > Right
//code for the comparator at the bottom of the file
bst = new BST(new MyComp1());
for(Integer n : a) bst.insert(n);
bst.preOrderTraversal();
System.out.println();
bst.inOrderTraversal();
System.out.println();
for(Integer n : bst) System.out.print(n);
System.out.println();
System.out.println(bst);
//testing restoring a tree from two given traversals
bst.restore(new Integer[] {11,8,6,4,7,10,19,43,31,29,37,49},
new Integer[] {4,6,7,8,10,11,19,29,31,37,43,49});
bst.preOrderTraversal();
System.out.println();
bst.inOrderTraversal();
System.out.println();
//testing diameter
System.out.println(\"diameter = \" + bst.diameter());
//testing width
System.out.println(\"width = \" + bst.width());
}
private Node root;
private Comparator comparator;
public BST()
{
root = null;
comparator = null;
}
public BST(Comparator comp)
{
root = null;
comparator = comp;
}
private int compare(T x, T y)
{
if(comparator == null) return x.compareTo(y);
else
return comparator.compare(x,y);
}
/*****************************************************
*
* INSERT
*
******************************************************/
public void insert(T data)
{
root = insert(root, data);
}
private Node insert(Node p, T toInsert)
{
if (p == null)
return new Node(toInsert);
if (compare(toInsert, p.data) == 0)
return p;
if (compare(toInsert, p.data) < 0)
p.left = insert(p.left, toInsert);
else
p.right = insert(p.right, toInsert);
return p;
}
/*****************************************************
*
* SEARCH
*
******************************************************/
public boolean search(T toSearch)
{
return search(root, toSearch);
}
private boolean search(Node p, T toSearch)
{
if (p == null)
return false;
else
if (compare(toSearch, p.data) == 0)
return true;
else
if (compare(toSearch, p.data) < 0)
return search(p.left, toSearch);
else
return search(p.right, toSearch);
}
/*****************************************************.
MAINCPP include ltiostreamgt include ltstringgt u.pdfadityastores21
MAIN.CPP
#include <iostream>
#include <string>
using namespace std;
#include "bstree.h"
// Prints a single string, used by FSTree::inorder to print all
// values in the tree in correct order.
void print_string (string s) { cout << s << endl; }
// Prints a single string preceeded by a number of hyphens, used by
// BSTree::preorder to print a visual representation of the tree.
void print_string_depth (string s, int n) {
for (int i = 0; i < n; i++)
cout << '-';
cout << s << endl;
}
int main () {
// Create a binary search tree.
BSTree<string> t;
// Insert some strings for testing.
t.insert("dog");
t.insert("bird");
t.insert("cat");
t.insert("turtle");
t.insert("giraffe");
t.insert("snake");
t.insert("deer");
t.insert("groundhog");
t.insert("horse");
// Output the values stored in the tree.
cout << "Values stored in the tree are:n";
t.inorder(print_string);
cout << "n";
cout << "The structure of the tree is as follows:n";
t.preorder(print_string_depth);
cout << "n";
}
BSTREE.h
#pragma once
// A Binary Search Tree implementation.
template <typename T>
class BSTree {
private:
// A node in the tree. Each node has pointers to its left and right nodes
// as well as its parent. When a node is created, the parent and data item
// must be provided.
class node {
public:
T data;
node* left;
node* right;
node* parent;
node (const T& d, node* p) {
parent = p;
data = d;
left = right = nullptr;
}
};
// Pointer to the root node. Initially this is null for an empty tree.
node* root;
// Copy the subtree of another BSTree object into this object. Used by
// the copy constructor and assignment operator.
void copy (node* p) {
if (p) { // If p points to a node...
insert(p->data); // Insert data item
copy(p->left); // Copy the left subtree
copy(p->right); // Copy the right subtree
}
}
// Destroy a node and all nodes in both subtrees. Called by the
// destructor.
void destroy (node* p) {
if (p) { // If p is not null...
destroy(p->left); // Destroy the left subtree
destroy(p->right); // Destroy the right subtree
delete p; // Destroy the node
}
}
// Helper function to determine if a data value is contained in the tree.
// Takes the data value being searched and a pointer to the node in the
// tree. Returns pointer to node in which data item is found, a null
// pointer otherwise.
node* find (const T& d, node* p) const {
// Given: p is a pointer to an existing node
if (d == p->data) // Is this the value we're looking for?
return p;
if (d < p->data) // Check left side, if null then not found
return p->left ? find(d, p->left) : nullptr;
return p->right ? find(d, p->right) : nullptr; // Check right side...
}
// Helper function to insert a data item into the tree. Takes the data
// and a pointer to a node in the tree. Recursively decends down the tree
// until position were insertion should take place is found.
void insert (const T& d, node* p) {
// Given: p is a pointer to an existing node (root of a subtree)
if (d < p->data) { // Insert into left subtree?
if (p->left) // Left.
(1)Objective Binary Search Tree traversal (2 points)Use traversal.pdfarihantmobileselepun
(1)Objective: Binary Search Tree traversal (2 points)
Use traversal.pptx as guidance to write a program to build a binary search tree Dictionary. I of
BST have the same data from each input record.
Download traversal-lab.pptx, inventory.txt, BinNode.java, BSTNode.java, BST.java,
Dictionary.java .
Perform specifications as follow:
(a)Provide Add, Delete and Retrieve functions for user to access the database. Reject duplicate
record when add a new record.
(b)Modify BST.java to add printpostOrder, printpreOrder methods.
(c)At the end, display inorder, postorder and preorder of the tree.
Codes:
/** Source code example for \"A Practical Introduction to Data
Structures and Algorithm Analysis, 3rd Edition (Java)\"
by Clifford A. Shaffer
Copyright 2008-2011 by Clifford A. Shaffer
*/
/** ADT for binary tree nodes */
public interface BinNode {
/** Get and set the element value */
public E element();
public void setElement(E v);
/** @return The left child */
public BinNode left();
/** @return The right child */
public BinNode right();
/** @return True if a leaf node, false otherwise */
public boolean isLeaf();
}
//********************************************************************
// StringTree.java
//
//********************************************************************
import java.util.*;
public class StringTree
{
private Node root;
//----------------------------------------------------------------
// Creates an initially empty tree.
//----------------------------------------------------------------
public StringTree()
{
root = null;
}
//----------------------------------------------------------------
// Adds a string to the tree.
//----------------------------------------------------------------
public void addString (String str)
{
root = addStringToSubTree(str, root);
}
//----------------------------------------------------------------
// Adds a string to the subtree with the given root node
//----------------------------------------------------------------
private Node addStringToSubTree (String str, Node node)
{
Node result = node;
if (node == null)
result = new Node(str);
// If the new string comes before the string in the node, add
// the new string to the left child. Otherwise, add it to the
// right child.
else
if (str.compareTo(node.value) < 0)
node.left = addStringToSubTree(str, node.left);
else
node.right = addStringToSubTree(str, node.right);
return result;
}
//----------------------------------------------------------------
// Prints the result of a depth-first traversal of the tree using
// recursion.
//----------------------------------------------------------------
public void traverseWithRecursion()
{
traverseWithRecursion(root);
}
//----------------------------------------------------------------
// Prints the elements in the specified tree using recursion.
//----------------------------------------------------------------
private void traverseWithRecursion (Node node)
{
if (node != null)
{
traverseWithRecursion (node.left);
System.
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
.
For the code below complete the preOrder() method so that it perform.pdfxlynettalampleyxc
For the code below complete the preOrder() method so that it performs a preOrder traversal of
the tree. For each node it traverses, it should call sb.append() to add a \"[\" the results of
traversing the subtree rooted at that node, and then a \"]\". You should add a space before the
results of the left and right child traversals, but only if the node exists.
code:
Solution
In preorder Nodes visited are in the order of
code:
package edu.buffalo.cse116;
import java.util.AbstractSet;
import java.util.Iterator;
public class BinarySearchTree> extends AbstractSet {
protected Entry root;
protected int size;
/**
* Initializes this BinarySearchTree object to be empty, to contain only
* elements of type E, to be ordered by the Comparable interface, and to
* contain no duplicate elements.
*/
public BinarySearchTree() {
root = null;
size = 0;
}
/**
* Initializes this BinarySearchTree object to contain a shallow copy of a
* specified BinarySearchTree object. The worstTime(n) is O(n), where n is the
* number of elements in the specified BinarySearchTree object.
*
* @param otherTree - the specified BinarySearchTree object that this
* BinarySearchTree object will be assigned a shallow copy of.
*/
public BinarySearchTree(BinarySearchTree otherTree) {
root = copy(otherTree.root, null);
size = otherTree.size;
}
/* Method to complete is here! */
public void preOrder(Entry ent, StringBuilder sb) {
preorder(root)
protected Entry copy(Entry p, Entry parent) {
if (p != null) {
Entry q = new Entry(p.element, parent);
q.left = copy(p.left, q);
q.right = copy(p.right, q);
return q;
}
return null;
} // method copy
@SuppressWarnings(\"unchecked\")
@Override
public boolean equals(Object obj) {
if (!(obj instanceof BinarySearchTree)) {
return false;
}
return equals(root, ((BinarySearchTree) obj).root);
}
public boolean equals(Entry p, Entry q) {
if ((p == null) || (q == null)) {
return p == q;
}
if (!p.element.equals(q.element)) {
return false;
}
if (equals(p.left, q.left) && equals(p.right, q.right)) {
return true;
}
return false;
}
/**
* Returns the size of this BinarySearchTree object.
*
* @return the size of this BinarySearchTree object.
*/
@Override
public int size() {
return size;
}
/**
* Iterator method will be implemented for a future
*
* @return an iterator positioned at the smallest element in this
* BinarySearchTree object.
*/
@Override
public Iterator iterator() {
throw new UnsupportedOperationException(\"Not implemented yet!\");
}
/**
* Determines if there is at least one element in this BinarySearchTree object
* that equals a specified element. The worstTime(n) is O(n) and
* averageTime(n) is O(log n).
*
* @param obj - the element sought in this BinarySearchTree object.
* @return true - if there is an element in this BinarySearchTree object that
* equals obj; otherwise, return false.
* @throws ClassCastException - if obj cannot be compared to the elements in
* this BinarySearchTree object.
* @throws NullPointerException - if obj is null.
*/
@Override
public .
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.
On the code which has a class in which I implementing a binary tree .pdfwasemanivytreenrco51
On the code which has a class in which I implementing a binary tree using an array. This array,
named store, stores Node in entries corresponding to
nodes in the tree and null if the node does not exist. Complete the countLeavesmethod so that it
returns the number of leaves in this tree.
Code:
Solution
import java.util.AbstractSet; import java.util.Arrays; import java.util.Iterator; import
java.util.NoSuchElementException; /** * Implementation of an abstract set using an array-
based binary tree. This is * used to help teach binary tree\'s and will have more details explained
in * future lectures. * * @author William J. Collins * @author Matthew Hertz * @param
Data type (which must be Comparable) of the elements in this tree. */ public class
ArrayBinaryTree> extends AbstractSet { /** Entry in the data store where the root node can be
found. */ private static final int ROOT = 0; /** Array used to store the nodes which consist of
this binary tree. */ protected Node[] store; /** Number of elements within the tree. */
protected int size; /** * Initializes this ArrayBinaryTree object to be empty. This creates the
array * in which items will be stored. */ @SuppressWarnings(\"unchecked\") public
ArrayBinaryTree() { store = new Node[63]; size = 0; } /** * Initializes this
ArrayBinaryTree object to contain a shallow copy of a * specified ArrayBinaryTree object.
The worstTime(n) is O(n), where n is the * number of elements in the specified
ArrayBinaryTree object. * * @param otherTree The tree which will be copied to create our
new tree, */ @SuppressWarnings(\"unchecked\") public ArrayBinaryTree(ArrayBinaryTree
otherTree) { store = (Node[]) Arrays.copyOf(otherTree.store, otherTree.store.length); size =
otherTree.size; } public int countLeaves() { } /** * Returns the size of this
ArrayBinaryTree object. * * @return the size of this ArrayBinaryTree object. */
@Override public int size() { return size; } /** * Returns an iterator that will return the
elements in this ArrayBinaryTree, * but without any specific ordering. * * @return Iterator
positioned at the smallest element in this ArrayBinaryTree * object. */ @Override
public Iterator iterator() { return new ArrayTreeIterator(); } /** * Determines if there is at
least one element in this ArrayBinaryTree object * that equals a specified element. The
worstTime(n) is O(n) and * averageTime(n) is O(log n). * * @param obj - the element
sought in this ArrayBinaryTree object. * @return true - if there is an element in this
ArrayBinaryTree object that * equals obj; otherwise, return false. * @throws
ClassCastException - if obj cannot be compared to the elements in * this
ArrayBinaryTree object. * @throws NullPointerException - if obj is null. */ @Override
public boolean contains(Object obj) { return getEntry(obj) != null; } /** * Ensures that
this ArrayBinaryTree object contains a specified element. The * worstTime(n) is O(n) for this
addition. * * @param element Element we want to be certain is contained within.
Objective Binary Search Tree traversal (2 points)Use traversal.pp.pdfsivakumar19831
Objective: Binary Search Tree traversal (2 points)
Use traversal.pptx as guidance to write a program to build a binary search tree Dictionary. Input
records from inventory.txt. Both key and Element of BST have the same data from each input
record.
public interface BinNode {
/** Get and set the element value */
public E element();
public void setElement(E v);
/** @return The left child */
public BinNode left();
/** @return The right child */
public BinNode right();
/** @return True if a leaf node, false otherwise */
public boolean isLeaf();
}
import java.lang.Comparable;
/** Binary Search Tree implementation for Dictionary ADT */
class BST, E>
implements Dictionary {
private BSTNode root; // Root of the BST
int nodecount; // Number of nodes in the BST
/** Constructor */
BST() { root = null; nodecount = 0; }
/** Reinitialize tree */
public void clear() { root = null; nodecount = 0; }
/** Insert a record into the tree.
@param k Key value of the record.
@param e The record to insert. */
public void insert(Key k, E e) {
root = inserthelp(root, k, e);
nodecount++;
}
// Return root
public BSTNode getRoot()
{
return root;
}
/** Remove a record from the tree.
@param k Key value of record to remove.
@return The record removed, null if there is none. */
public E remove(Key k) {
E temp = findhelp(root, k); // First find it
if (temp != null) {
root = removehelp(root, k); // Now remove it
nodecount--;
}
return temp;
}
/** Remove and return the root node from the dictionary.
@return The record removed, null if tree is empty. */
public E removeAny() {
if (root == null) return null;
E temp = root.element();
root = removehelp(root, root.key());
nodecount--;
return temp;
}
/** @return Record with key value k, null if none exist.
@param k The key value to find. */
public E find(Key k) { return findhelp(root, k); }
/** @return The number of records in the dictionary. */
public int size() { return nodecount; }
private E findhelp(BSTNode rt, Key k) {
if (rt == null) return null;
if (rt.key().compareTo(k) > 0)
return findhelp(rt.left(), k);
else if (rt.key().compareTo(k) == 0) return rt.element();
else return findhelp(rt.right(), k);
}
/** @return The current subtree, modified to contain
the new item */
private BSTNode inserthelp(BSTNode rt,
Key k, E e) {
if (rt == null) return new BSTNode(k, e);
if (rt.key().compareTo(k) > 0)
rt.setLeft(inserthelp(rt.left(), k, e));
else
rt.setRight(inserthelp(rt.right(), k, e));
return rt;
}
/** Remove a node with key value k
@return The tree with the node removed */
private BSTNode removehelp(BSTNode rt,Key k) {
if (rt == null) return null;
if (rt.key().compareTo(k) > 0)
rt.setLeft(removehelp(rt.left(), k));
else if (rt.key().compareTo(k) < 0)
rt.setRight(removehelp(rt.right(), k));
else { // Found it
if (rt.left() == null) return rt.right();
else if (rt.right() == null) return rt.left();
else { // Two children
BSTNode temp = getmin(rt.right());
rt.setElement(temp.element());
rt.setKey(temp.key());
rt.setRight(deletemin(rt.right(.
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.
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.
A)B) C++ program to create a Complete Binary tree from its Lin.pdfanton291
A)
B)
// C++ program to create a Complete Binary tree from its Linked List
// Representation
#include
#include
#include
using namespace std;
// Linked list node
struct ListNode
{
int data;
ListNode* next;
};
// Binary tree node structure
struct BinaryTreeNode
{
int data;
BinaryTreeNode *left, *right;
};
// Function to insert a node at the beginning of the Linked List
void push(struct ListNode** head_ref, int new_data)
{
// allocate node and assign data
struct ListNode* new_node = new ListNode;
new_node->data = new_data;
// link the old list off the new node
new_node->next = (*head_ref);
// move the head to point to the new node
(*head_ref) = new_node;
}
// method to create a new binary tree node from the given data
BinaryTreeNode* newBinaryTreeNode(int data)
{
BinaryTreeNode *temp = new BinaryTreeNode;
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
// converts a given linked list representing a complete binary tree into the
// linked representation of binary tree.
void convertList2Binary(ListNode *head, BinaryTreeNode* &root)
{
// queue to store the parent nodes
queue q;
// Base Case
if (head == NULL)
{
root = NULL; // Note that root is passed by reference
return;
}
// 1.) The first node is always the root node, and add it to the queue
root = newBinaryTreeNode(head->data);
q.push(root);
// advance the pointer to the next node
head = head->next;
// until the end of linked list is reached, do the following steps
while (head)
{
// 2.a) take the parent node from the q and remove it from q
BinaryTreeNode* parent = q.front();
q.pop();
// 2.c) take next two nodes from the linked list. We will add
// them as children of the current parent node in step 2.b. Push them
// into the queue so that they will be parents to the future nodes
BinaryTreeNode *leftChild = NULL, *rightChild = NULL;
leftChild = newBinaryTreeNode(head->data);
q.push(leftChild);
head = head->next;
if (head)
{
rightChild = newBinaryTreeNode(head->data);
q.push(rightChild);
head = head->next;
}
// 2.b) assign the left and right children of parent
parent->left = leftChild;
parent->right = rightChild;
}
}
// Utility function to traverse the binary tree after conversion
void inorderTraversal(BinaryTreeNode* root)
{
if (root)
{
inorderTraversal( root->left );
cout << root->data << \" \";
inorderTraversal( root->right );
}
}
// Driver program to test above functions
int main()
{
// create a linked list shown in above diagram
struct ListNode* head = NULL;
push(&head, 36); /* Last node of Linked List */
push(&head, 30);
push(&head, 25);
push(&head, 15);
push(&head, 12);
push(&head, 10); /* First node of Linked List */
BinaryTreeNode *root;
convertList2Binary(head, root);
cout << \"Inorder Traversal of the constructed Binary Tree is: \ \";
inorderTraversal(root);
return 0;
}
c)
#include
#include
using namespace std;
template
class bintree
{
bintree *left;
T data;
bintree *right;
public :
bintree()
{
left=right=NULL;
}
void create();
void preorder();
void inorder();
void pos.
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;
}.
ReversePoem.java ---------------------------------- public cl.pdfravikapoorindia
ReversePoem.java :-
---------------------------------
public class ReversePoem {
/*This programs has you display a pessimistic poem from a list of phrases*/
// and then reverse the phrases to find another more optimistic poem.
public static void main(String[] args) throws Exception
{
//Queue object
MyQueue queue = new MyQueue<>();
//Stack object
MyStack stack = new MyStack<>();
//String buffer to apppend all Strings
StringBuffer sb = new StringBuffer();
// Create a single String object from the 16 Strings below
String set1 = \"I am part of a lost generation#and I refuse to believe that#\";
sb.append(set1);
String set2 = \"I can change the world#I realize this may be a shock but#\";
sb.append(set2);
String set3 = \"\'Happiness comes from within\'#is a lie, and#\";
sb.append(set3);
String set4 = \"\'Money will make me happy\'#So in 30 years I will tell my children#\";
sb.append(set4);
String set5 = \"they are not the most important thing in my life#\";
sb.append(set5);
String set6 = \"My employer will know that#I have my priorities straight because#\";
sb.append(set6);
String set7 = \"work#is more important than#family#I tell you this#\";
sb.append(set7);
String set8 = \"Once upon a time#Families stayed together#\";
sb.append(set8);
String set9 = \"but this will not be true in my era#\";
sb.append(set9);
String set10 = \"This is a quick fix society#Experts tell me#\";
sb.append(set10);
String set11 = \"30 years from now, I will be celebrating the 10th anniversary of my
divorce#\";
sb.append(set11);
String set12 = \"I do not concede that#I will live in a country of my own making#\";
sb.append(set12);
String set13 = \"In the future#Environmental destruction will be the norm#\";
sb.append(set13);
String set14 = \"No longer can it be said that#My peers and I care about this earth#\";
sb.append(set14);
String set15 = \"It will be evident that#My generation is apathetic and lethargic#\";
sb.append(set15);
String set16 = \"It is foolish to presume that#There is hope#\";
sb.append(set16);
String finalString = sb.toString();
String itmes[] = finalString.split(\"#\");
System.out.println(\"========== Original Phrase ==============\");
for(int i = 0 ; i < itmes.length;i++){
queue.enqueue(itmes[i]);
System.out.println(itmes[i]);
}
for(int i = 0 ; i < itmes.length;i++){
stack.push(queue.dequeue());
}
System.out.println(\"========== Reverse Phrase ==============\");
for(int i = 0 ; i < itmes.length;i++){
System.out.println(stack.pop());
}
/* You are given a list of phrases in Strings; the phrases
are separated by pound signs: \'#\':
1. Create a single String object from this list.
2. Then, split the String of phrases into an array of
phrases using the String split method.
3. Display a poem by walking through the array and
displaying each phrase one per line.
4. And, at the same time, place each phrase on a
MyQueue object using only the enqueue method.
5. After all the phrases have been placed on the queue,
transfer the phrases from the MyQueue object to a
MyS.
Create an implementation of a binary tree using the recursive appr.pdffederaleyecare
\"Create an implementation of a binary tree using the recursive approach introduced in the
chapter. In this approach, each node is a binary tree. Thus a binary tree contains a reference to
the element stored at its root as well as references to its left and right subtrees. You may also
want to include a reference to its parent.\" p.741
You need to use the locally implemented binary tree. This means you need to have a \"jsjf\"
subfolder with at least these files: BinaryTreeADT.java, LinkedBinaryTree.java,
BinaryTreeNode.java, and the exceptions sub-subfolder.
Test/demonstrate your binary tree by doing the following:
Request file name from user,
Read an infix expression from file,
Build binary expression tree,
Display binary expression tree,
Evaluate binary expression tree,
Display result.
##############################################
Note a typical input file can be found here
##############################################
# Version 0.2, fully parenthesized.
# This is a comment
((9 + 4) * 5) + (4 - (6 + 3))
# Note first expression should evaluate to 60
((42 + ( 10 - 2 )) + ( 5 * 3 )) / 6
# Note second expression should evaluate to 65 / 6 or 10 (integer division)
##############################################
My program is below but the out put is incorrect
##############################################
StringTree.java
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Stack;
import jsjf.BinaryTreeNode;
import jsjf.LinkedBinaryTree;
public class StringTree extends LinkedBinaryTree {
public StringTree(String rootStr, StringTree leftSubtree, StringTree rightSubtree) {
root = new BinaryTreeNode(rootStr, leftSubtree, rightSubtree);
} // StringTree
public StringTree(File f) {
Stack leftStack = new Stack(), rightStack = new Stack();
// stacks of left and right subtrees of nodes
Scanner scan;
// scanner for reading from the file
String nodeType,
nodeStr;
// string contained in the current node
boolean hasLeftChild, hasRightChild;
// true if the current node has a left or right child
StringTree leftSubtree, rightSubtree,
// left and right subtrees of the current node
subtree;
// subtree having the current node as its root
// Create a scanner for reading from the file.
try {
scan = new Scanner(f);
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
root = null;
System.out.println(\"\ \"+\"The program has terminated......\");
System.exit(0);
return;
}
// Read the file and build a tree from the bottom up.
while (scan.hasNext()) {
// Input information about a tree node.
nodeType = scan.next();
hasLeftChild = (scan.next().equalsIgnoreCase(\"y\"));
hasRightChild = (scan.next().equalsIgnoreCase(\"y\"));
nodeStr = scan.next();
// Determine the left and right subtrees of the subtree
// having the node as its root.
if (hasLeftChild)
leftSubtree = leftStack.pop();
else
leftSubtree = null;
if (hasRightChild)
rightSubtree = rightStack.pop();
else
rightSubtree = null;
.
Data Structures in C++I am really new to C++, so links are really .pdfrohit219406
Data Structures in C++
I am really new to C++, so links are really hard topic for me. It would be nice if you can provide
explanations of what doubly linked lists are and of some of you steps... Thank you
In this assignment, you will implement a doubly-linked list class, together with some list
operations. To make things easier, you’ll implement a list of int, rather than a template class.
Solution
A variable helps us to identify the data. For ex: int a = 5; Here 5 is identified through variable a.
Now, if we have collection of integers, we need some representation to identify them. We call it
array. For ex: int arr[5]
This array is nothing but a Data Structure.
So, a Data Structure is a way to group the data.
There are many Data Structures available like Arrays, Linked List, Doubly-Linked list, Stack,
Queue, etc.
Doubly-Linked list are the ones where you can traverse from the current node both in left and
right directions.
Why so many different types of Data Structures are required ?
Answer is very simple, grouping of data, storage of data and accessing the data is different.
For example, in case of Arrays we store all the data in contiguous locations.
What if we are not able to store the data in contiguous locations because we have huge data.
Answer is go for Linked List/Doubly-Linked list.
Here we can store the data anywhere and link the data through pointers.
I will try to provide comments for the code you have given. May be this can help you.
#pragma once
/*
dlist.h
Doubly-linked lists of ints
*/
#include
class dlist {
public:
dlist() { }
// Here we are creating a NODE, it has a integer value and two pointers.
// One pointer is to move to next node and other to go back to previous node.
struct node {
int value;
node* next;
node* prev;
};
// To return head pointer, i.e. start of the Doubly-Linked list.
node* head() const { return _head; }
// To return Tail pointer, i.e. end of the Doubly-Linked list.
node* tail() const { return _tail; }
// **** Implement ALL the following methods ****
// Returns the node at a particular index (0 is the head).
node* at(int index){
int cnt = 0;
struct node* tmp = head();
while(tmp!=NULL)
{
if (cnt+1 == index)
return tmp;
tmp = tmp->next;
}
}
// Insert a new value, after an existing one
void insert(node *previous, int value){
// check if the given previous is NULL
if (previous == NULL)
{
printf(\"the given previous node cannot be NULL\");
return;
}
// allocate new node
struct node* new_node =(struct node*) malloc(sizeof(struct node));
// put in the data
new_node->data = new_data;
// Make next of new node as next of previous
new_node->next = previous->next;
// Make the next of previous as new_node
previous->next = new_node;
// Make previous as previous of new_node
new_node->prev = previous;
// Change previous of new_node\'s next node
if (new_node->next != NULL)
new_node->next->prev = new_node;
}
// Delete the given node
void del(node* which){
struct node* head_ref = head();
/* base case */
if(*head_ref == NUL.
Write a program that accepts an arithmetic expression of unsigned in.pdfJUSTSTYLISH3B2MOHALI
Write a program that accepts an arithmetic expression of unsigned integers in postfix notation
and builds the arithmetic expression tree that represents that expression. From that tree, the
corresponding fully parenthesized infix expression should be displayed and a file should be
generated that contains the three address format instructions. This topic is discussed in the week
4 reading in module 2, section II-B. The main class should create the GUI shown below:
Pressing the Construct Tree button should cause the tree to be constructed and using that tree, the
corresponding infix expression should be displayed and the three address instruction file should
be generated. The postfix expression input should not be required to have spaces between every
token. Note in the above example that 9+- are not separated by spaces. The above example
should produce the following output file containing the three address instructions:
Add R0 5 9
Sub R1 3
R0 Mul R2 2 3
Div R3 R1 R2
Inheritance should be used to define the arithmetic expression tree. At a minimum, it should
involve three classes: an abstract class for the tree nodes and two derived classes, one for
operand nodes and another for operator nodes. Other classes should be included as needed to
accomplish good object-oriented design. All instance data must be declared as private.
You may assume that the expression is syntactically correct with regard to the order of operators
and operands, but you should check for invalid tokens, such as characters that are not valid
operators or operands such as 2a, which are not valid integers. If an invalid token is detected a
RuntimeException should be thrown and caught by the main class and an appropriate error
message should be displayed. Three Adddress Generator Enter Postfix Expression 359 2 3
Construct Tree Infix Expression ((3-(5 9))/ (2* 3
Solution
#include
#include
#include
#include
#include
struct TREE //Structure to represent a tree
{
char data;
struct TREE *right,*left,*root;
};
typedef TREE tree; /* Stack Using Linked List */
struct Stack //Structure to represent Stack
{
struct TREE *data;
struct Stack *next,*head,*top; //Pointers to next node,head and top
};
typedef struct Stack node;
node *Nw; //Global Variable to represent node
void initialize(node *&n)
{
n = new node;
n -> next = n -> head = n -> top = NULL;
}
void create(node *n)
{
Nw = new node; //Create a new node
Nw -> next = NULL; //Initialize next pointer field
if(n -> head == NULL) //if first node
{
n -> head = Nw; //Initialize head
n -> top = Nw; //Update top
}
}
void push(node *n,tree *ITEM)
{
node *temp = n -> head;
if(n -> head == NULL) //if First Item is Pushed to Stack
{
create(n); //Create a Node
n -> head -> data = ITEM; //Insert Item to head of List
n -> head = Nw;
return; //Exit from Function
}
create(n); //Create a new Node
Nw -> data = ITEM; //Insert Item
while(temp -> next != NULL)
temp = temp -> next; //Go to Last Node
temp -> next = Nw; //Point New node
n -> top = Nw; //Upda.
Assignment 9 (Parent reference for BST) Redefine TreeNode by adding .pdfFootageetoffe16
Assignment 9 (Parent reference for BST) Redefine TreeNode by adding a reference to a node’s
parent, as shown below:
BST.TreeNode
#element
#left : TreeNode
#right: TreeNode
#parent: TreeNode
Implement the insert and delete methods in BST class to update the parent for each node in the
tree.
Add the following new method in BST:
/** Return the node for the specific element.
* Return null if the element is not in the tree. */
private TreeNode getNode(E element)
/** Returns true if the node for the element is a lead */
private boolean isLeaf(E element)
/** Returns the path of the element from the specific element to the root in an array list */
public ArrayList getPath(E e)
Write a test program that prompts the user to enter 10 integers, adds them to the tree, deletes the
first integer from the tree, and displays the paths for all leaf nodes.
Sample run
Enter 10 integers :
45 54 67 56 50 45 23 59 23 67
[50, 54, 23]
[59, 56, 67, 54, 23]
Solution
import java.util.NoSuchElementException; public class TreeSet> implements Set {
private TreeNode root; private int size; // Constructs an empty set. public
TreeSet() { root = null; size = 0; } // Adds the given value to this
set, if it was not already in the set. // If the element is already a member of this set, adding it
again has no effect. public void add(E value) { root = add(root, value); }
// private recursive helper for add // uses the \"x = change(x)\" pattern: // pass in
current state of root // return out desired new state of root private TreeNode
add(TreeNode node, E value) { if (node == null) { node = new
TreeNode(value); // reached dead end; put new node here size++; }
else if (value.compareTo(node.data) > 0) { node.right = add(node.right, value);
} else if (value.compareTo(node.data) < 0) { node.left = add(node.left,
value); } // else a duplicate; do nothing return node; } // Returns
true if this set contains the given element value. public boolean contains(E value) {
return contains(root, value); } // private recursive helper for contains private
boolean contains(TreeNode node, E value) { if (node == null) { return
false; } else if (value.compareTo(node.data) > 0) { return
contains(node.right, value); } else if (value.compareTo(node.data) < 0) {
return contains(node.left, value); } else { // value.equals(root.data);
found it! return true; } } // Returns the minimum value in this
set. // Throws a NoSuchElementException if this set is empty. public E getMin() {
if (root == null) { throw new NoSuchElementException(\"empty tree\");
} return getMin(root); } // private recursive helper for getMin
private E getMin(TreeNode node) { if (node.left == null) { return
node.data; } else { return getMin(node.left); } }
// Returns true if this set does not contain any elements. public boolean isEmpty() {
return size == 0; } // Prints all elements of this tree in a left-to-right order (in-order)
traversal. public void print() { print(root); } // private recursive helper
for print private void print(TreeNode .
5. Design and implement a method contains 2 for BinarySearchTree, fu.pdframbagra74
5. Design and implement a method contains 2 for BinarySearchTree, functionall equivalent to
the contains method, that does not use recursion.
show the driver code and do this in java
this is the binarysearchtree
import java.util.*; // Iterator, Comparator
public class BinarySearchTree implements BSTInterface
{
protected BSTNode root; // reference to the root of this BST
protected Comparator comp; // used for all comparisons
protected boolean found; // used by remove
public BinarySearchTree()
// Precondition: T implements Comparable
// Creates an empty BST object - uses the natural order of elements.
{
root = null;
comp = new Comparator()
{
public int compare(T element1, T element2)
{
return ((Comparable)element1).compareTo(element2);
}
};
}
public BinarySearchTree(Comparator comp)
// Creates an empty BST object - uses Comparator comp for order
// of elements.
{
root = null;
this.comp = comp;
}
public boolean isFull()
// Returns false; this link-based BST is never full.
{
return false;
}
public boolean isEmpty()
// Returns true if this BST is empty; otherwise, returns false.
{
return (root == null);
}
public T min()
// If this BST is empty, returns null;
// otherwise returns the smallest element of the tree.
{
if (isEmpty())
return null;
else
{
BSTNode node = root;
while (node.getLeft() != null)
node = node.getLeft();
return node.getInfo();
}
}
public T max()
// If this BST is empty, returns null;
// otherwise returns the largest element of the tree.
{
if (isEmpty())
return null;
else
{
BSTNode node = root;
while (node.getRight() != null)
node = node.getRight();
return node.getInfo();
}
}
private int recSize(BSTNode node)
// Returns the number of elements in subtree rooted at node.
{
if (node == null)
return 0;
else
return 1 + recSize(node.getLeft()) + recSize(node.getRight());
}
public int size()
// Returns the number of elements in this BST.
{
return recSize(root);
}
public int size2()
// Returns the number of elements in this BST.
{
int count = 0;
if (root != null)
{
LinkedStack> nodeStack = new LinkedStack>();
BSTNode currNode;
nodeStack.push(root);
while (!nodeStack.isEmpty())
{
currNode = nodeStack.top();
nodeStack.pop();
count++;
if (currNode.getLeft() != null)
nodeStack.push(currNode.getLeft());
if (currNode.getRight() != null)
nodeStack.push(currNode.getRight());
}
}
return count;
}
private boolean recContains(T target, BSTNode node)
// Returns true if the subtree rooted at node contains info i such that
// comp.compare(target, i) == 0; otherwise, returns false.
{
if (node == null)
return false; // target is not found
else if (comp.compare(target, node.getInfo()) < 0)
return recContains(target, node.getLeft()); // Search left subtree
else if (comp.compare(target, node.getInfo()) > 0)
return recContains(target, node.getRight()); // Search right subtree
else
return true; // target is found
}
public boolean contains (T target)
// Returns true if this BST contains a node with info i such that
// comp.compare(target, i) == 0; otherwise, re.
Similar to Once you have all the structures working as intended- it is time to co.docx (20)
PARTICIPANTS PROFILE ANSWER ABOVE MENTIONED QUESTIONS BY TAKING CARE.docxfarrahkur54
PARTICIPANTS PROFILE
ANSWER ABOVE MENTIONED QUESTIONS BY TAKING CAREGIVERS OF ADULTS IN LONG TERM FACILITY AS AUDIENCE
TRAINING FOR [ PRESSURE ULCER ]
PLEASE PROVIDE CITATIONS AND REFERENCES - VERYIMPORTANT
.
Part3- Offline traffic monitoring In this part will use a PCAP file to.docxfarrahkur54
Part3: Offline traffic monitoring In this part will use a PCAP file to examine the network traffic (offline traffic monitoring) using three IDS tools - Snort - Suricata - Zeek The PCAP file with the name part3.pcap (attached with the project files) containing a captured network traffic for some company having a web site and 256 addresses in the range (192.168.6.0 - 192.168.6.255). The IP address for the network gateway (edge router) is ( 192.168.6.1 ) . The captured network traffic is for some period of time when an attacker started to perform intrusion against the company network. The suspicious address is 192.168.5.55, which conducted a multi-stage attack starting with reconnaissance. A kill chain representing multi-stage attack is a systematic process to target and engage an attacker to perform the desired attack. The following steps are the typical stages followed by any professional attacker. 1. Reconnaissance - Research, identification and selection of targets, often represented as crawling Internet websites such as conference proceedings and mailing lists for email addresses, social relationships, or information on specific technologies. 2. Weaponization - Coupling a remote access trojan with an exploit into a deliverable payload, typically by means of an automated tool (weaponizer). Increasingly, client application data files such as Adobe Portable Document Format (PDF) or Microsoft Office documents serve as the weaponized deliverable. 3. Delivery - Transmission of the weapon to the targeted environment. The three most prevalent delivery vectors for weaponized payloads by APT actors, as observed by the Lockheed Martin Computer Incident Response Team (LM-CIRT) for the years 2004-2010, are email attachments, websites, and USB removable media. 4. Exploitation - After the weapon is delivered to victim host, exploitation triggers intruders' code. Most often, exploitation targets an application or operating system vulnerability, but it could also more simply exploit the users themselves or leverage an operating system feature that auto-executes code. 5. Installation - Installation of a remote access trojan or backdoor on the victim system allows the adversary to maintain persistence inside the environment. 6. Command and Control (C2) - Typically, compromised hosts must beacon outbound to an Internet controller server to establish a C2 channel. APT malware especially requires manual interaction rather than conduct activity automatically. Once the C 2 channel establishes, intruders have "hands on the keyboard" access inside the target environment. 7. Actions on Objectives - Only now, after progressing through the first six phases, can intruders take actions to achieve their original objectives. Typically, this objective is data exfiltration which involves collecting, encrypting and extracting information from the victim environment; violations of data integrity or availability are potential objectives as well. Alternatively, the intruders may.
Participation is a requirement of this course- Students provide one po.docxfarrahkur54
Participation is a requirement of this course. Students provide one post introducing their key concept from the chapter(s) for the week in 200 words or less, with references to the textbook and two other supporting materials in APA format (e.g., Nelson & Quick, 2018, p. 17).
Provide a thoughtful and meaningful approach to posts and ensure quality contributions:
Stay on topic, and ensure thoughts and ideas are logically constructed,
Show respect and inclusion, and
Ensure correct grammar and sentence structure.
.
Partners Johnny and Daniel each have capital balances of $95-000- Migu.docxfarrahkur54
Partners Johnny and Daniel each have capital balances of $95 , 000 . Miguel invests $110 , 000 for a 1/3 interest in the partnership. How much of Miguel's investment is credited to his capital account? $300 , 000 $100 , 000 $95 , 000 $110 , 000 Millie and David have capital accounts totalling $100 , 000 and $150 , 000 respectively in a partnership at the beginning of the year. Regarding the division of net income (losses), the partnership agreement states that each partner earns 10% interest on their capital account balance and gives salary allowances of $25 , 000 to Millie and $10 , 000 to David, with the remaining income (loss) being shared equally. How much of a net income of $80 , 000 will be allocated to Millie? $45 , 000 $40 , 000 $25 , 000 $35 , 000 Elliot makes $10 per hour. He worked 42 hours last week. According to FLSA, how much should his gross pay be? $420 $630 $400 $430
.
Parthians- write one to two paragraphs on the significance of this ite.docxfarrahkur54
Parthians, write one to two paragraphs on the significance of this item.
Explain how this item is a cause or a consequence of some event.
Explain how this item exemplified some trend or movement or ideology.
Explain how this item ties into one of our class themes.
Explain any other way this item is significant.
.
Overview You are required to prepare a Data Entry report which provide.docxfarrahkur54
Overview You are required to prepare a Data Entry report which provides a full data sheet (using FinSas spread sheets) for a specific non-financial company of your choice using the most recent five years of annual reports / data available. The selected annual reports/data must: 1. Be written in English. 2. Be obtained from any credible source such as Datastream, Bloomberg, Thomson One, the company's website, etc. 3. You can use any type of additional data to support your analysis, taking into consideration its credibility and appropriate referencing. 4. Use accounting rules and standards (IFRS/US GAAP) consistent to the ones used for the competitor company used as your benchmark. Important Notes: 1. You will choose your company via Learn Ultra on a first-come first-served basis and you cannot select the same company as another student. You do not need to register your choice of a competitor company. 2. You must fully check the accessibility of annual reports and data before choosing your company. 3. Calculations for the different ratios and vertical/horizontal analysis are required to be done using the FINSAS software. The output of FINSAS should be attached to your report in the appendices section. 4. You must not depend on the disclosed ratios in the annual reports. You are required to prepare these ratios on your own with the assistance of FINSAS. 5. Graphical presentation of your findings can help in your evaluation. Tables in the body of the work should present key information that you refer to in the text and be clearly set out. 6. The module leader needs to be informed and to approve the company you'll be choosing for your project, using the available Google sheet available on Learn Uitra.
.
Overton Company has gathered the following information-Compute equival.docxfarrahkur54
Overton Company has gathered the following information. Compute equivalent units of production for materials and for conversion costs. eTextbook and Media Determine the unit costs of production. (Round unit costs to 2 decimal places, e.g. 2.25.) Show the assignment of costs to units transferred out and in process. Transferred out Ending work in process 5
.
Option #1- Form Validation in JavaScript 1- In your text editor- open.docxfarrahkur54
Option #1: Form Validation in JavaScript
1. In your text editor, open the index.htm file from the HandsOnProject6-1 folder in the Chapter06 folder , add your name and today's date where indicated in the comment section, and then save the file. 2. Create a new document in your editor, add JavaScript comments containing the text Hands-on Project6-1, your name, and today's date, and then save the file to the HandsOnProject6-1 folder with the name script.js. 3. Return to the htm file in your browser, within the body section, just before the closing /body tag, add a script element, and then specify the file script.js as the source. 4. In the opening form tag, add code to disable browser-based validation, and then save your changes. 5. In the script.js file, add code instructing processors to interpret the contents in strict mode, and then create a global variable named formValidity and set its value to true. 6. Add the following function to validate the required form elements: 7. Add the following function to create an event lister for the submit event. 8. Add the following function to trigger validation of required fields when the Submit button is clicked: 9. Add the following code to call the createEventListeners() function when the page finishes loading. 1 /* run setup functions when page finishes loading */ 2 if (window.addEventListner) \{ 3 window.addEventListner("load", createEventListenres, false); 4 \} else if (window.attachEvent) \{ 5 window.attachEvent ("onload", createEventListeners); 6 \} 10. Save your changes to script.js, open index.htm in a browser, and then test various combinations of invalid and valid data to ensure that the scripts you wrote behave as you expect. Debug your code as necessary until it functions correctly. 11. Returntoscript.js in your editor, and then add the following function to validate input elements with the number type: 1/ validate number fields for older browsers % 2 function validate Numbers () \{ 3 var numberInputs = document.querySelectorAll (H"\#contactinfo input[type=number]"); 4 var elementCount = numberInputs.length; 5 var numErrorDiv = document.getElementByld("numErrorText"); 6 var numbersValidity = true; 7 var currentElement; 8 try { 12. In the validateForm() function, add a call to the validateNumbers() function as follows: 13. Save your changes to script.js, open index.htm in a browser, and then test various combinations of invalid and valid data, including nonnumeric entries in number fields, to ensure that the scripts you wrote behave as you expect. Debug your code as necessary until it functions correctly.
.
Over 1 million Americans make a living working for advertising and pub.docxfarrahkur54
Over 1 million Americans make a living working for advertising and public relations companies. Now, more than ever, companies are seeking individuals who can manage Internet advertising campaigns dealing with social media and other digital channels. Do young people have an advantage over older folks in this arena? How? How can you leverage your knowledge of social media and the Internet in general to become more valuable to an advertiser?
.
Oscar is suing John for $1000 dollars but the judge sees that their ar.docxfarrahkur54
Oscar is suing John for $1000 dollars but the judge sees that their argument is beyond financial, it seems more like a friendship gone wrong. The judge orders Oscar to visit a neutral person to facilitate their communication with the goal of creating a mutually acceptable agreement. The mutually acceptable agreement is not enforceable by law but more of a contract between the two parties. This is an example of? Statute of Friuds Subpoena Binding Arbitration Superior Court System Mediation
.
Organizational Behavior Chapter 5 - Perception and Indigidual Decision.docxfarrahkur54
Organizational Behavior Chapter 5 : Perception and Indigidual Decision Making
myth or science? "No One Thinks They're Biased"
Organizational Behavior Chapter 5 : Perception and Indigidual Decision Making
.
ook at the mean- median- mode- and standard deviation and describe how.docxfarrahkur54
ook at the mean, median, mode, and standard deviation and describe how these measures of central tendency indicates whether the distribution of women are normal or skewed. How does the mean, median, and mode scores indicate if the distribution is normal or skewed?
Mean 19.93
Median 20
Mode 19
Standard Deviation 4.30
Kurtosis 0.03
Skewness -0.46
Minimum 11
Maximum 27
.
Option #1- Creating a GUI Bank Balance Application Create a simple Gr.docxfarrahkur54
Option #1: Creating a GUI Bank Balance Application
Create a simple Graphical User Interface (GUI) Bank Balance application. The application must obtain the BankAccount balance from a user, and then display that balance within a JPanel when the user selects a button. The program should allow for the user to deposit and withdraw funds from their account using a simple interface. The remaining balance in the account should be displayed before exiting the program. Ensure that your application includes the following components:
JPanel
JButton
ActionListener
Submit screenshots of your program's execution and output. Include all appropriate source code in a zip file.
.
Operational Metrics and Benchmarking in Healthcare- What are common op.docxfarrahkur54
Operational Metrics and Benchmarking in Healthcare. What are common operational metrics utilized by healthcare organizations? Where do they come from and why are they important? Next, describe how benchmarks are developed and how they can be useful in calculating results of operational metrics?
.
One of the duties and functions of the joint OHS committee is to ensur.docxfarrahkur54
One of the duties and functions of the joint OHS committee is to ensure that regular inspections are being carried out in the workplace. Typically the committee will perform inspections as part of their regular activities. What 'class of inspection' would this fall into? A) Supervisor inspection B) Employee inspection C) Special inspection D) Planned general inspection
.
One of the deadliest heart conditions is a disturbance in heart rhythm.docxfarrahkur54
One of the deadliest heart conditions is a disturbance in heart rhythm known as ventricular fibrillation, in which the myocytes of the ventricles depolarize and contract individually. How are the cells of the heart supposed to contract? (Hint: Think about the functions of the intercalated discs.) Why would it be deadly to have cardiac myocytes of the ventricles contracting individually?
.
Palestine last event orientationfvgnh .pptxRaedMohamed3
An EFL lesson about the current events in Palestine. It is intended to be for intermediate students who wish to increase their listening skills through a short lesson in power point.
How to Split Bills in the Odoo 17 POS ModuleCeline George
Bills have a main role in point of sale procedure. It will help to track sales, handling payments and giving receipts to customers. Bill splitting also has an important role in POS. For example, If some friends come together for dinner and if they want to divide the bill then it is possible by POS bill splitting. This slide will show how to split bills in odoo 17 POS.
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?
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.
The Indian economy is classified into different sectors to simplify the analysis and understanding of economic activities. For Class 10, it's essential to grasp the sectors of the Indian economy, understand their characteristics, and recognize their importance. This guide will provide detailed notes on the Sectors of the Indian Economy Class 10, using specific long-tail keywords to enhance comprehension.
For more information, visit-www.vavaclasses.com
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!
The French Revolution, which began in 1789, was a period of radical social and political upheaval in France. It marked the decline of absolute monarchies, the rise of secular and democratic republics, and the eventual rise of Napoleon Bonaparte. This revolutionary period is crucial in understanding the transition from feudalism to modernity in Europe.
For more information, visit-www.vavaclasses.com
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.
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.
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.
Once you have all the structures working as intended- it is time to co.docx
1. 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() {
2. 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) {
3. 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 == null && root.right == null) {
return 1;
}
// If the root has children, we recursively count the number of leaf nodes in both the
// left and right subtrees and return the sum
return countLeafNodes(root.left) + countLeafNodes(root.right);
4. }
/**
* Checks if the tree is a full tree.
*
* @param t The root of the tree.
* @return
*/
private boolean isFull(BinaryNode<AnyType> root) {
// If the root is null, it means the tree is empty, so it is not full
if (root == null) {
return false;
}
// If the root has no children, it means the tree only has one node, which makes it a full tree
if (root.left == null && root.right == null) {
return true;
}
// If the root has only one child, it is not a full tree
if (root.left == null || root.right == null) {
return false;
}
// If the root has two children, we recursively check both the left and right subtrees
// to see if they are both full
return isFull(root.left) && isFull(root.right);
5. }
public void insert(AnyType x) {
root = insert(x, root);
}
/**
* Counts the number of leaf nodes in a tree.
*
* @return
*/
public int countLeafNodes() {
return countLeafNodes(root);
}
/**
* Checks if the tree is full.
*
* @return
*/
public boolean isFull() {
return isFull(root);
}
/**
* Remove from the tree. Nothing is done if x is not found.
*
6. * @param x the item to remove.
*/
public void remove(AnyType x) {
root = remove(x, root);
}
/**
* Internal method to remove from a subtree.
*
* @param x the item to remove.
* @param root the node that roots the subtree.
* @return the new root of the subtree.
*/
protected BinaryNode<AnyType> remove(AnyType x, BinaryNode<AnyType> root) {
// If item not found, do nothing.
if (root == null) {
return root;
}
int compareResult = x.compareTo(root.element);
if (compareResult < 0) {
root.left = remove(x, root.left);
} else if (compareResult > 0) {
root.right = remove(x, root.right);
} // Two children.
7. else if (root.left != null && root.right != null) {
root.element = findMin(root.right).element;
root.right = remove(root.element, root.right);
} // Zero or one child.
else {
root = (root.left != null) ? root.left : root.right;
}
return root;
}
/**
* Find an item in the tree.
*
* @param x the item to search for.
* @return true if not found.
*/
public boolean contains(AnyType x) {
return contains(x, root);
}
private boolean contains(AnyType x, BinaryNode<AnyType> root) {
if (root == null) {
return false;
}
int compareResult = x.compareTo(root.element);
8. if (compareResult < 0) {
return contains(x, root.left);
} else if (compareResult > 0) {
return contains(x, root.right);
} else {
return true; // Match with current node
}
}
/**
* Find the smallest item in the tree.
*
* @return smallest item or null if empty.
* @throws Exception
*/
public AnyType findMin() throws Exception {
if (isEmpty()) {
throw new Exception();
}
return findMin(root).element;
}
private BinaryNode<AnyType> findMin(BinaryNode<AnyType> root) {
if (root == null) {
return null;
9. } else if (root.left == null) {
return root; // found the leftmost node
} else {
return findMin(root.left);
}
}
/**
* Test if the tree is logically empty.
*
* @return true if empty, false otherwise.
*/
public boolean isEmpty() {
return root == null;
}
/**
* Calculate the height of the tree.
*
* @return the height.
*/
public int height() {
return height(this.root);
}
/**
10. * Internal method to compute height of a subtree.
*
* @param root the node that roots the subtree.
* @return
*/
protected int height(BinaryNode<AnyType> root) {
return root == null ? -1
: 1 + Math.max(height(root.left), height(root.right));
}
public BinaryNode<AnyType> getRoot() {
return root;
}
public void setRoot(BinaryNode<AnyType> root) {
this.root = root;
}
public void printSideways(String label) {
System.out.println(
"n-------------------------------" + label + "----------------------------");
printSideways(root, "");
}
private void printSideways(BinaryNode root,
String indent) {
if (root != null) {
11. printSideways(root.right, indent + " ");
System.out.println(indent + root.element);
printSideways(root.left, indent + " ");
}
}
}
public class AVLTree<AnyType extends Comparable<? super AnyType>> extends
BinarySearchTree<AnyType> {
public AVLTree() {
super();
this.BALANCE_FACTOR = 1;
}
private final int BALANCE_FACTOR;
/**
*
* @param root The root of the BST
* @return The balanced tree.
*/
private BinaryNode<AnyType> balance(BinaryNode<AnyType> root) {
if (root == null) {
return root;
}
private BinaryNode<AnyType> balance(BinaryNode<AnyType> root) {
if (root == null) {
return root;
}
int heightDiff = height(root.left) - height(root.right);
if (heightDiff > BALANCE_FACTOR) {
// case 1: left-left
12. if (height(root.left.left) >= height(root.left.right)) {
root = rotateRightWithLeftChild(root);
}
// case 2: left-right
else {
root = doubleLeftRight(root);
}
} else if (heightDiff < -BALANCE_FACTOR) {
// case 3: right-right
if (height(root.right.right) >= height(root.right.left)) {
root = rotateLeftWithRightChild(root);
}
// case 4: right-left
else {
root = doubleRightLeft(root);
}
}
return root;
}
return root;
}
/**
* Rotate binary tree node with left child. For AVL trees, this is a single
* rotation for case 1.
*/
private BinaryNode<AnyType> rotateRightWithLeftChild(BinaryNode<AnyType> k2) {
13. BinaryNode<AnyType> k1 = k2.left;
k2.left = k1.right;
k1.right = k2;
return k1;
}
/**
* Rotate binary tree node with right child. For AVL trees, this is a single
* rotation for case 4.
*/
private BinaryNode<AnyType> rotateLeftWithRightChild(BinaryNode<AnyType> k1) {
BinaryNode<AnyType> k2 = k1.right;
k1.right = k2.left;
k2.left = k1;
return k2;
}
/**
* Double rotate binary tree node: first left child with its right child;
* then node k3 with new left child. For AVL trees, this is a double
* rotation for case 2.
*/
private BinaryNode<AnyType> doubleLeftRight(BinaryNode<AnyType> k3) {
k3.left = rotateLeftWithRightChild(k3.left);
return rotateRightWithLeftChild(k3);
}
/**
* Double rotate binary tree node: first right child with its left child;
* then node k1 with new right child. For AVL trees, this is a double
* rotation for case 3.
*/
private BinaryNode<AnyType> doubleRightLeft(BinaryNode<AnyType> k1) {
k1.right = rotateRightWithLeftChild(k1.right);
return rotateLeftWithRightChild(k1);
}
/**
* Insert into the tree; duplicates are ignored.
14. *
* @param x the item to insert.
*/
@Override
public void insert(AnyType x) {
root = insert(x, root);
}
/**
* Internal method to insert into a subtree.
*
* @param x the item to insert.
* @param root the node that roots the subtree.
* @return the new root of the subtree.
*/
@Override
protected BinaryNode<AnyType> insert(AnyType x, BinaryNode<AnyType> root) {
return balance(super.insert(x, root));
}
/**
* Remove from the tree. Nothing is done if x is not found.
*
* @param x the item to remove.
*/
@Override
public void remove(AnyType x) {
root = remove(x, root);
}
/**
* Internal method to remove from a subtree.
*
* @param x the item to remove.
* @param root the node that roots the subtree.
* @return the new root of the subtree.
*/
@Override
protected BinaryNode<AnyType> remove(AnyType x, BinaryNode<AnyType> root) {
return balance(super.remove(x, root));
}
public void checkBalance() {
checkBalance(root);
}
15. private int checkBalance(BinaryNode<AnyType> root) {
if (root == null) {
return -1;
} else {
int heightLeft = checkBalance(root.left);
int heightRight = checkBalance(root.right);
if (Math.abs(height(root.left) - height(root.right)) > BALANCE_FACTOR
|| height(root.left) != heightLeft || height(root.right) != heightRight) {
System.out.println("!!!!!!UNBALANCED TREE!!!!!!");
}
}
return height(root);
}
}