The document extends a Binary Search Tree (BST) interface to include a new public method called leafCount that returns the number of leaf nodes in the tree. It also provides the BinarySearchTree and BSTInterface files that implement the BST with methods for common operations like adding and removing nodes, and traversing the tree in different orders.
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.
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.
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& .
There is BinarySearchTree class. When removing a node from a BST, we.pdfDhanrajsolanki2091
There is BinarySearchTree class. When removing a node from a BST, we can replace it with
either its predecessor or its successor. Complete the predecessor() method
so that it returns the node that comes immediately before e. Hint: the work needed to find the
predecessor is a mirror image of what is required to find a node\'s
successor, so use successor() as a resource.
BinarySearchTree class:
Solution
import java.util.AbstractSet;
import java.util.Iterator;
public class BinarySearchTree> extends AbstractSet {
protected BTNode 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;
}
protected BTNode copy(BTNode p, BTNode parent) {
if (p != null) {
BTNode q = new BTNode(p.element, parent);
q.left = copy(p.left, q);
q.right = copy(p.right, q);
return q;
}
return null;
} // method copy
/**
* Finds the predecessor of a specified BTNode object in this BinarySearchTree. The
worstTime(n) is O(n) and
* averageTime(n) is constant.
*
* @param e - the BTNode object whose successor is to be found.
* @return the successor of e, if e has a successor; otherwise, return null.
*/
protected BTNode predecessor(BTNode e) {
if (e == null) {
return null;
} else if (e.left != null) {
// successor is leftmost BTNode in right subtree of e
BTNode p = e.left;
while (p.right != null) {
p = p.right;
}
return p;
} // e has a right child
else {
// go up the tree to the right as far as possible, then go up
// to the left.
BTNode p = e.parent;
BTNode ch = e;
while ((p != null) && (ch == p.left)) {
ch = p;
p = p.parent;
} // while
return p;
} // e has no left child
// method successor
}
@SuppressWarnings(\"unchecked\")
@Override
public boolean equals(Object obj) {
if (!(obj instanceof BinarySearchTree)) {
return false;
}
return equals(root, ((BinarySearchTree) obj).root);
} // method 1-parameter equals
public boolean equals(BTNode p, BTNode 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
* Bina.
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
}
/* ...
Once you have all the structures working as intended- it is time to co.docxfarrahkur54
Once you have all the structures working as intended, it is time to compare the
performances of the 2. Use runBenchmark() to start.
a. First, generate an increasing number (N) of random integers (1000, 5000, 10000,
50000, 75000, 100000, 500000 or as far as your computing power will let you)
i. Time and print how long it takes to insert the random integers into an initially
empty BST. Do not print the tree.
You can get a random list using the java class Random, located in
java.util.Random. To test the speed of the insertion algorithm, you should use
the System.currentTimeMillis() method, which returns a long that contains the
current time (in milliseconds). Call System.currentTimeMillis() before and after
the algorithm runs and subtract the two times. (Instant.now() is an alternative
way of recording the time.)
ii. Time and print how long it takes to insert the same random integers into an
initially empty AVL tree. Do not print the tree.
iii. If T(N) is the time function, how does the growth of TBST(N) compare with the
growth of TAVL(N)?
Plot a simple graph to of time against N for the two types of BSTs to visualize
your results.
b. Second, generate a list of k random integers. k is also some large value.
i. Time how long it takes to search your various N-node BSTs for all k random
integers. It does not matter whether the search succeeds.
ii. Time how long it takes to search your N-node AVL trees for the same k random
integers.
iii. Compare the growth rates of these two search time-functions with a graph the
same way you did in part a.
public class BinarySearchTree<AnyType extends Comparable<? super AnyType>> {
protected BinaryNode<AnyType> root;
public BinarySearchTree() {
root = null;
}
/**
* Insert into the tree; duplicates are ignored.
*
* @param x the item to insert.
* @param root
* @return
*/
protected BinaryNode<AnyType> insert(AnyType x, BinaryNode<AnyType> root) {
// If the root is null, we've reached an empty leaf node, so we create a new node
// with the value x and return it
if (root == null) {
return new BinaryNode<>(x, null, null);
}
// Compare the value of x to the value stored in the root node
int compareResult = x.compareTo(root.element);
// If x is less than the value stored in the root node, we insert it into the left subtree
if (compareResult < 0) {
root.left = insert(x, root.left);
}
// If x is greater than the value stored in the root node, we insert it into the right subtree
else if (compareResult > 0) {
root.right = insert(x, root.right);
}
// If x is equal to the value stored in the root node, we ignore it since the tree does not allow duplicates
return root;
}
/**
* Counts the number of leaf nodes in this tree.
*
* @param t The root of the tree.
* @return
*/
private int countLeafNodes(BinaryNode<AnyType> root) {
// If the root is null, it means the tree is empty, so we return 0
if (root == null) {
return 0;
}
// If the root has no children, it means it is a leaf node, so we return 1
if (root.left == .
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.
BSTNode.Java Node class used for implementing the BST. .pdfinfo189835
BSTNode.Java:
/**
* Node class used for implementing the BST.
*
* DO NOT MODIFY THIS FILE!!
*
* @author CS 1332 TAs
* @version 1.0
*/
public class BSTNode> {
private T data;
private BSTNode left;
private BSTNode right;
/**
* Constructs a BSTNode with the given data.
*
* @param data the data stored in the new node
*/
BSTNode(T data) {
this.data = data;
}
/**
* Gets the data.
*
* @return the data
*/
T getData() {
return data;
}
/**
* Gets the left child.
*
* @return the left child
*/
BSTNode getLeft() {
return left;
}
/**
* Gets the right child.
*
* @return the right child
*/
BSTNode getRight() {
return right;
}
/**
* Sets the data.
*
* @param data the new data
*/
void setData(T data) {
this.data = data;
}
/**
* Sets the left child.
*
* @param left the new left child
*/
void setLeft(BSTNode left) {
this.left = left;
}
/**
* Sets the right child.
*
* @param right the new right child
*/
void setRight(BSTNode right) {
this.right = right;
}
}
BST.Java:
import java.util.NoSuchElementException;
/**
* Your implementation of a BST.
*/
public class BST> {
/*
* Do not add new instance variables or modify existing ones.
*/
private BSTNode root;
private int size;
/*
* Do not add a constructor.
*/
/**
* Adds the data to the tree.
*
* This must be done recursively.
*
* The new data should become a leaf in the tree.
*
* Traverse the tree to find the appropriate location. If the data is
* already in the tree, then nothing should be done (the duplicate
* shouldn't get added, and size should not be incremented).
*
* Should be O(log n) for best and average cases and O(n) for worst case.
*
* @param data The data to add to the tree.
* @throws java.lang.IllegalArgumentException If data is null.
*/
public void add(T data) {
// WRITE YOUR CODE HERE (DO NOT MODIFY METHOD HEADER)!
}
/**
* Removes and returns the data from the tree matching the given parameter.
*
* This must be done recursively.
*
* There are 3 cases to consider:
* 1: The node containing the data is a leaf (no children). In this case,
* simply remove it.
* 2: The node containing the data has one child. In this case, simply
* replace it with its child.
* 3: The node containing the data has 2 children. Use the SUCCESSOR to
* replace the data. You should use recursion to find and remove the
* successor (you will likely need an additional helper method to
* handle this case efficiently).
*
* Do NOT return the same data that was passed in. Return the data that
* was stored in the tree.
*
* Hint: Should you use value equality or reference equality?
*
* Must be O(log n) for best and average cases and O(n) for worst case.
*
* @param data The data to remove.
* @return The data that was removed.
* @throws java.lang.IllegalArgumentException If data is null.
* @throws java.util.NoSuchElementException If the data is not in the tree.
*/
public T remove(T data) {
// WRITE YOUR CODE HERE (DO NOT MODIFY METHOD HEADER)!
}
/**
* Returns the root of the tree.
*
* For grading purposes only. You shouldn't need to use this met.
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.
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.
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& .
There is BinarySearchTree class. When removing a node from a BST, we.pdfDhanrajsolanki2091
There is BinarySearchTree class. When removing a node from a BST, we can replace it with
either its predecessor or its successor. Complete the predecessor() method
so that it returns the node that comes immediately before e. Hint: the work needed to find the
predecessor is a mirror image of what is required to find a node\'s
successor, so use successor() as a resource.
BinarySearchTree class:
Solution
import java.util.AbstractSet;
import java.util.Iterator;
public class BinarySearchTree> extends AbstractSet {
protected BTNode 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;
}
protected BTNode copy(BTNode p, BTNode parent) {
if (p != null) {
BTNode q = new BTNode(p.element, parent);
q.left = copy(p.left, q);
q.right = copy(p.right, q);
return q;
}
return null;
} // method copy
/**
* Finds the predecessor of a specified BTNode object in this BinarySearchTree. The
worstTime(n) is O(n) and
* averageTime(n) is constant.
*
* @param e - the BTNode object whose successor is to be found.
* @return the successor of e, if e has a successor; otherwise, return null.
*/
protected BTNode predecessor(BTNode e) {
if (e == null) {
return null;
} else if (e.left != null) {
// successor is leftmost BTNode in right subtree of e
BTNode p = e.left;
while (p.right != null) {
p = p.right;
}
return p;
} // e has a right child
else {
// go up the tree to the right as far as possible, then go up
// to the left.
BTNode p = e.parent;
BTNode ch = e;
while ((p != null) && (ch == p.left)) {
ch = p;
p = p.parent;
} // while
return p;
} // e has no left child
// method successor
}
@SuppressWarnings(\"unchecked\")
@Override
public boolean equals(Object obj) {
if (!(obj instanceof BinarySearchTree)) {
return false;
}
return equals(root, ((BinarySearchTree) obj).root);
} // method 1-parameter equals
public boolean equals(BTNode p, BTNode 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
* Bina.
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
}
/* ...
Once you have all the structures working as intended- it is time to co.docxfarrahkur54
Once you have all the structures working as intended, it is time to compare the
performances of the 2. Use runBenchmark() to start.
a. First, generate an increasing number (N) of random integers (1000, 5000, 10000,
50000, 75000, 100000, 500000 or as far as your computing power will let you)
i. Time and print how long it takes to insert the random integers into an initially
empty BST. Do not print the tree.
You can get a random list using the java class Random, located in
java.util.Random. To test the speed of the insertion algorithm, you should use
the System.currentTimeMillis() method, which returns a long that contains the
current time (in milliseconds). Call System.currentTimeMillis() before and after
the algorithm runs and subtract the two times. (Instant.now() is an alternative
way of recording the time.)
ii. Time and print how long it takes to insert the same random integers into an
initially empty AVL tree. Do not print the tree.
iii. If T(N) is the time function, how does the growth of TBST(N) compare with the
growth of TAVL(N)?
Plot a simple graph to of time against N for the two types of BSTs to visualize
your results.
b. Second, generate a list of k random integers. k is also some large value.
i. Time how long it takes to search your various N-node BSTs for all k random
integers. It does not matter whether the search succeeds.
ii. Time how long it takes to search your N-node AVL trees for the same k random
integers.
iii. Compare the growth rates of these two search time-functions with a graph the
same way you did in part a.
public class BinarySearchTree<AnyType extends Comparable<? super AnyType>> {
protected BinaryNode<AnyType> root;
public BinarySearchTree() {
root = null;
}
/**
* Insert into the tree; duplicates are ignored.
*
* @param x the item to insert.
* @param root
* @return
*/
protected BinaryNode<AnyType> insert(AnyType x, BinaryNode<AnyType> root) {
// If the root is null, we've reached an empty leaf node, so we create a new node
// with the value x and return it
if (root == null) {
return new BinaryNode<>(x, null, null);
}
// Compare the value of x to the value stored in the root node
int compareResult = x.compareTo(root.element);
// If x is less than the value stored in the root node, we insert it into the left subtree
if (compareResult < 0) {
root.left = insert(x, root.left);
}
// If x is greater than the value stored in the root node, we insert it into the right subtree
else if (compareResult > 0) {
root.right = insert(x, root.right);
}
// If x is equal to the value stored in the root node, we ignore it since the tree does not allow duplicates
return root;
}
/**
* Counts the number of leaf nodes in this tree.
*
* @param t The root of the tree.
* @return
*/
private int countLeafNodes(BinaryNode<AnyType> root) {
// If the root is null, it means the tree is empty, so we return 0
if (root == null) {
return 0;
}
// If the root has no children, it means it is a leaf node, so we return 1
if (root.left == .
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.
BSTNode.Java Node class used for implementing the BST. .pdfinfo189835
BSTNode.Java:
/**
* Node class used for implementing the BST.
*
* DO NOT MODIFY THIS FILE!!
*
* @author CS 1332 TAs
* @version 1.0
*/
public class BSTNode> {
private T data;
private BSTNode left;
private BSTNode right;
/**
* Constructs a BSTNode with the given data.
*
* @param data the data stored in the new node
*/
BSTNode(T data) {
this.data = data;
}
/**
* Gets the data.
*
* @return the data
*/
T getData() {
return data;
}
/**
* Gets the left child.
*
* @return the left child
*/
BSTNode getLeft() {
return left;
}
/**
* Gets the right child.
*
* @return the right child
*/
BSTNode getRight() {
return right;
}
/**
* Sets the data.
*
* @param data the new data
*/
void setData(T data) {
this.data = data;
}
/**
* Sets the left child.
*
* @param left the new left child
*/
void setLeft(BSTNode left) {
this.left = left;
}
/**
* Sets the right child.
*
* @param right the new right child
*/
void setRight(BSTNode right) {
this.right = right;
}
}
BST.Java:
import java.util.NoSuchElementException;
/**
* Your implementation of a BST.
*/
public class BST> {
/*
* Do not add new instance variables or modify existing ones.
*/
private BSTNode root;
private int size;
/*
* Do not add a constructor.
*/
/**
* Adds the data to the tree.
*
* This must be done recursively.
*
* The new data should become a leaf in the tree.
*
* Traverse the tree to find the appropriate location. If the data is
* already in the tree, then nothing should be done (the duplicate
* shouldn't get added, and size should not be incremented).
*
* Should be O(log n) for best and average cases and O(n) for worst case.
*
* @param data The data to add to the tree.
* @throws java.lang.IllegalArgumentException If data is null.
*/
public void add(T data) {
// WRITE YOUR CODE HERE (DO NOT MODIFY METHOD HEADER)!
}
/**
* Removes and returns the data from the tree matching the given parameter.
*
* This must be done recursively.
*
* There are 3 cases to consider:
* 1: The node containing the data is a leaf (no children). In this case,
* simply remove it.
* 2: The node containing the data has one child. In this case, simply
* replace it with its child.
* 3: The node containing the data has 2 children. Use the SUCCESSOR to
* replace the data. You should use recursion to find and remove the
* successor (you will likely need an additional helper method to
* handle this case efficiently).
*
* Do NOT return the same data that was passed in. Return the data that
* was stored in the tree.
*
* Hint: Should you use value equality or reference equality?
*
* Must be O(log n) for best and average cases and O(n) for worst case.
*
* @param data The data to remove.
* @return The data that was removed.
* @throws java.lang.IllegalArgumentException If data is null.
* @throws java.util.NoSuchElementException If the data is not in the tree.
*/
public T remove(T data) {
// WRITE YOUR CODE HERE (DO NOT MODIFY METHOD HEADER)!
}
/**
* Returns the root of the tree.
*
* For grading purposes only. You shouldn't need to use this met.
Help to implement delete_node get_succ get_pred walk and.pdfcontact32
Help to implement delete_node, get_succ, get_pred, walk, and tree_search in the script
following the given structure:
#include "bst.h"
// ---------------------------------------
// Node class
// Default constructor
Node::Node() {
// TODO: Implement this
key = 0;
parent = nullptr;
left = nullptr;
right = nullptr;
}
// Constructor
Node::Node(int in) {
// TODO: Implement this
key = in;
parent = nullptr;
left = nullptr;
right = nullptr;
}
// Destructor
Node::~Node() {
// TODO: Implement this
delete left;
delete right;
}
// Add parent
void Node::add_parent(Node* in) {
// TODO: Implement this
parent = in;
}
// Add to left of current node
void Node::add_left(Node* in) {
// TODO: Implement this
left = in;
if (in != nullptr) {
in->add_parent(this);
}
}
// Add to right of current node
void Node::add_right(Node* in) {
// TODO: Implement this
right = in;
if (in != nullptr) {
in->add_parent(this);
}
}
// Get key
int Node::get_key()
{
// TODO: Implement this
return key;
}
// Get parent node
Node* Node::get_parent()
{
// TODO: Implement this
return parent;
}
// Get left node
Node* Node::get_left()
{
// TODO: Implement this
return left;
}
// Get right node
Node* Node::get_right()
{
// TODO: Implement this
return right;
}
// Print the key to ostream to
// Do not change this
void Node::print_info(ostream& to)
{
to << key << endl;
}
// ---------------------------------------
// ---------------------------------------
// BST class
// Walk the subtree from the given node
void BST::inorder_walk(Node* in, ostream& to)
{
// TODO: Implement this
if (in != nullptr) {
inorder_walk(in->get_left(), to);
in->print_info(to);
inorder_walk(in->get_right(), to);
}
}
// Constructor
BST::BST()
{
// TODO: Implement this
root = nullptr;
}
// Destructor
BST::~BST()
{
// TODO: Implement this
delete root;
}
// Insert a node to the subtree
void BST::insert_node(Node* in)
{
// TODO: Implement this
Node* curr = root;
Node* par = nullptr;
while (curr != nullptr) {
par = curr;
if (in->get_key() < curr->get_key()) {
curr = curr->get_left();
} else {
curr = curr->get_right();
}
}
in->add_parent(par);
if (par == nullptr) {
root = in;
} else if (in->get_key() < par->get_key()) {
par->add_left(in);
} else {
par->add_right(in);
}
}
// Delete a node to the subtree
void BST::delete_node(Node* out)
{
// TODO: Implement this
}
// minimum key in the BST
Node* BST::tree_min()
{
// TODO: Implement this
return get_min(root);
}
// maximum key in the BST
Node* BST::tree_max()
{
// TODO: Implement this
return get_max(root);
}
// Get the minimum node from the subtree of given node
Node* BST::get_min(Node* in)
{
// TODO: Implement this
if (in == nullptr) {
return nullptr;
}
while (in->get_left() != nullptr) {
in = in->get_left();
}
return in;
}
// Get the maximum node from the subtree of given node
Node* BST::get_max(Node* in)
{
// TODO: Implement this
if (in == nullptr) {
return nullptr;
}
while (in->get_right() != nullptr) {
in = in->get_right();
}
return in;
}
// Get successor of the given node
Node* BS.
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 ...
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.
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 .
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.
Java Foundations StackADT-java --- - Defines the interface to a stack.docxVictorXUQGloverl
Java Foundations
StackADT.java
/**
* Defines the interface to a stack collection.
*
* @author Java Foundations
* @version 4.0
*/
public interface StackADT<T> {
/**
* Adds the specified element to the top of this stack.
*
* @param element element to be pushed onto the stack
*/
public void push(T element);
/**
* Removes and returns the top element from this stack.
*
* @return the element removed from the stack
* @throws EmptyCollectionException if the stack is empty
*/
public T pop();
/**
* Returns the top element of this stack without removing it from the stack.
*
* @return the element on top of the stack. It is not removed from the stack
* @throws EmptyCollectionException if the stack is empty
*/
public T peek();
/**
* Returns true if this stack contains no elements.
*
* @return true if the stack is empty, false if the stack is not empty
*/
public boolean isEmpty();
/**
* Returns the number of elements in this stack.
*
* @return the number of elements in the stack
*/
public int size();
}
QueueADT.java
/**
* QueueADT defines the interface to a queue collection.
*
* @author Java Foundation
* @version 4.0
*/
public interface QueueADT<T> {
/**
* Adds one element to the rear of this queue.
*
* @param element the element to be added to the rear of the queue
*/
public void enqueue(T element);
/**
* Removes and returns the element at the front of this queue.
*
* @return the element at the front of the queue
* @throws EmptyCollectionException if the queue is empty
*/
public T dequeue();
/**
* Returns without removing the element at the front of this queue.
*
* @return the first element in the queue
* @throws EmptyCollectionException if the queue is empty
*/
public T first();
/**
* Returns true if this queue contains no elements.
*
* @return true if the queue is empty, false if the queue is not empty
*/
public boolean isEmpty();
/**
* Returns the number of elements in this queue.
*
* @return the number of elements in the queue
*/
public int size();
}
LinkedDeque.java
public class LinkedDeque<T> implements QueueADT<T>, StackADT<T>, DequeADT<T> {
// inner class for a double linked list node
private class DNode<T> {
private T element;
private DNode<T> prev, next;
}
// data fields for the LinkedDeque class
private DNode<T> front, rear;
private int size;
// deque interface methods
@Override
public void addFirst(T element) {
// create a new node and set it up
DNode<T> newNode = new DNode<T>();
newNode.element = element; // from param to new node obj
newNode.prev = newNode.next = null;
if(this.isEmpty()) {
// we are making the only node in the deque
this.rear = this.front = newNode;
} else {
// there already exists a new node
// so, put the new node before the front node
newNode.next = this.front;
this.front.prev = newNode;
this.front = newNode;
}
this.size++;
}
@Override
public T removeFirst() {
T grabbedElt = this.getFirst(); // checks for empty for us
if.
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 .
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.
Using NetBeansImplement a queue named QueueLL using a Linked List .pdfsiennatimbok52331
Using NetBeans
Implement a queue named QueueLL using a Linked List (same as we did for the stack). This
implementation must be used in all the following problems.
Implement a queue QueueST using a stack (use StackLL).
Test your implementations in the main with examples.
Solution
Answer:-
import java.util.*;
/* Class Node */
class Node
{
protected int data;
protected Node link;
/* Constructor */
public Node()
{
link = null;
data = 0;
}
/* Constructor */
public Node(int d,Node n)
{
data = d;
link = n;
}
/* Function to set link to next Node */
public void setLink(Node n)
{
link = n;
}
/* Function to set data to current Node */
public void setData(int d)
{
data = d;
}
/* Function to get link to next node */
public Node getLink()
{
return link;
}
/* Function to get data from current Node */
public int getData()
{
return data;
}
}
/* Class linkedQueue */
class linkedQueue
{
protected Node front, rear;
public int size;
/* Constructor */
public linkedQueue()
{
front = null;
rear = null;
size = 0;
}
/* Function to check if queue is empty */
public boolean isEmpty()
{
return front == null;
}
/* Function to get the size of the queue */
public int getSize()
{
return size;
}
/* Function to insert an element to the queue */
public void insert(int data)
{
Node nptr = new Node(data, null);
if (rear == null)
{
front = nptr;
rear = nptr;
}
else
{
rear.setLink(nptr);
rear = rear.getLink();
}
size++ ;
}
/* Function to remove front element from the queue */
public int remove()
{
if (isEmpty() )
throw new NoSuchElementException(\"Underflow Exception\");
Node ptr = front;
front = ptr.getLink();
if (front == null)
rear = null;
size-- ;
return ptr.getData();
}
/* Function to check the front element of the queue */
public int peek()
{
if (isEmpty() )
throw new NoSuchElementException(\"Underflow Exception\");
return front.getData();
}
/* Function to display the status of the queue */
public void display()
{
System.out.print(\"\ Queue = \");
if (size == 0)
{
System.out.print(\"Empty\ \");
return ;
}
Node ptr = front;
while (ptr != rear.getLink() )
{
System.out.print(ptr.getData()+\" \");
ptr = ptr.getLink();
}
System.out.println();
}
}
/* Class LinkedQueueImplement */
public class LinkedQueueImplement
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
/* Creating object of class linkedQueue */
linkedQueue lq = new linkedQueue();
/* Perform Queue Operations */
System.out.println(\"Linked Queue Test\ \");
char ch;
do
{
System.out.println(\"\ Queue Operations\");
System.out.println(\"1. insert\");
System.out.println(\"2. remove\");
System.out.println(\"3. peek\");
System.out.println(\"4. check empty\");
System.out.println(\"5. size\");
int choice = scan.nextInt();
switch (choice)
{
case 1 :
System.out.println(\"Enter integer element to insert\");
lq.insert( scan.nextInt() );
break;
case 2 :
try
{
System.out.println(\"Removed Element = \"+ lq.remove());
}
catch (Exception e)
{
System.out.println(\"Error : \" + e.getMessage());
}
break;
case 3 .
For this project, write a program that stores integers in a binary.docxbudbarber38650
For this project, write a program that stores integers in a binary search tree.
The tree should use the BTNode class which is provided.
Write a test program that generates 20 random numbers in the range of -50 to 50 to build the tree and then uses preorderPrint,
inorderPrint, and postOrderPrint to display the contents of the tree.
To get an A implement a new method for the BTNode class which creates a Java vector class to contain
the data from all the nodes in the tree. The specification for this method is provided in the BTNode file.
Details about the Java vector class are provided in Appendix D, although the only vector method you'll use is addElement.
Also specify and implement in-order and post-order traversals and answer the question which of the
three new methods creates a vector with the entries sorted from smallest to largest?
Your test program should display the vectors created by your new methods rather than the print methods of BTNode.
// File: BTNode.java from the package edu.colorado.nodes
// Complete documentation is available from the BTNode link in:
// http://www.cs.colorado.edu/~main/docs/
package BTNode;
import java.util.Vector;
/******************************************************************************
* A <CODE>BTNode<<E></CODE> provides a node for a binary tree. Each node
* contains a piece of data (which is a reference to an E object) and references
* to a left and right child. The references to children may be null to indicate
* that there is no child. The reference stored in a node can also be null.
*
* <dl><dt><b>Limitations:</b> <dd>
* Beyond <CODE>Int.MAX_VALUE</CODE> elements, <CODE>treeSize</CODE>, is
* wrong.
*
* <dt><b>Java Source Code for this class:</b><dd>
* <A HREF="../../../../edu/colorado/nodes/BTNode.java">
* http://www.cs.colorado.edu/~main/edu/colorado/nodes/BTNode.java </A>
*
* @author Michael Main
* <A HREF="mailto:[email protected]"> ([email protected]) </A>
*
* @version
* Jul 22, 2005
******************************************************************************/
public class BTNode<E>
{
// Invariant of the BTNode<E> class:
// 1. Each node has one reference to an E Object, stored in the instance
// variable data.
// 2. The instance variables left and right are references to the node's
// left and right children.
private E data;
private BTNode<E> left, right;
/**
* Initialize a <CODE>BTNode</CODE> with a specified initial data and links
* children. Note that a child link may be the null reference,
* which indicates that the new node does not have that child.
* @param <CODE>initialData</CODE>
* the initial data of this new node
* @param <CODE>initialLeft</CODE>
* a reference to the left child of this new node--this reference may be null
* to indicate that there is no node after this new node.
* @param <CODE>initialRight</CODE>
.
Please fix my errors class Iterator public Construc.pdfkitty811
Please fix my errors
class Iterator
{
public:
/// Constructor taking a head and tail pointer; YOU'RE WELCOME
Iterator(Node<T> *head, Node<T> *tail) : head_(head), tail_(tail)
{
cursor_ = end();
}
/// Constructor taking a head, tail, and cursor pointer; YOU'RE WELCOME
Iterator(Node<T> *head, Node<T> *tail, Node<T> *cursor) : head_(head), tail_(tail),
cursor_(cursor) {}
/// Get a pointer to the head node, or end() if this list is empty
Node<T> *begin() { return head_; }
/// Get a node pointer representing "end" (aka "depleted"). Probably want to just use nullptr.
Node<T> *end() { return nullptr; }
/// Get the node to which this iterator is currently pointing
Node<T> *getCursor() { return cursor_; }
/**
* Assignment operator
* Return a copy of this Iterator, after modification
*/
Iterator &operator=(const Iterator &other)
{
head_ = other.head_;
tail_ = other.tail_;
cursor_ = other.cursor_;
return *this;
}
/**
* Comparison operator
* Returns true if this iterator is equal to the other iterator, false otherwise
*/
bool operator==(const Iterator &other)
{
return cursor_ == other.cursor_;
}
/**
* Inequality comparison operator
* Returns true if this iterator is not equal to the other iterator, false otherwise
*/
bool operator!=(const Iterator &other)
{
return !(*this == other);
}
/**
* Prefix increment operator
* Return a copy of this Iterator, after modification
*/
Iterator &operator++()
{
cursor_ = cursor_->getNext();
return *this;
}
/*** Postfix increment
* Return a copy of this Iterator, BEFORE it was modified
*/
Iterator operator++(int)
{
Iterator copy(*this);
++(*this);
return copy;
}
/*** Prefix decrement operator
* Return a copy of this Iterator, after modification
*/
Iterator &operator--()
{
cursor_ = cursor_->getPrev();
return *this;
}
/**
* Postfix decrement operator
* Return a copy of this Iterator BEFORE it was modified
*/
Iterator operator--(int)
{
Iterator copy = *this;
--(*this);
return copy;
}
/**
* AdditionAssignment operator
* Return a copy of the current iterator, after modification
*/
Iterator operator+=(size_t add)
{
for (size_t i = 0; i < add && cursor_ != nullptr; ++i)
{
cursor_ = cursor_->getNext();
}
return *this;
}
/**
* SubtractionAssignment operator
* Return a copy of the current iterator, after modification
*/
Iterator operator-=(size_t sub)
{
for (size_t i = 0; i < sub && cursor_ != nullptr; ++i)
{
cursor_ = cursor_->getPrev();
}
return *this;
}
/**
* AdditionAssignment operator, supporting positive or negative ints
*/
Iterator operator+=(int add)
{
if (add > 0)
{
for (int i = 0; i < add && cursor_ != nullptr; ++i)
{
cursor_ = cursor_->getNext();
}
}
else
{
for (int i = 0; i > add && cursor_->getPrev() != nullptr; --i)
{
cursor_ = cursor_->getPrev();
}
}
return *this;
}
/**
* SubtractionAssignment operator, supporting positive or negative ints
*/
Iterator operator-=(int subtract)
{
// This function adds an integer to the current iterators position in the list,
if (subtract > 0)
{
for (int i = 0; i < subtract && cursor_.
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 ...
(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.
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(.
Implement the following specification of UnsortedType using circular.pdfudit652068
Implement the following specification of UnsortedType using circular linked list as the
implementation structure.
*** I have seen this question answered here before but it is not a good answer. Can someone
please give me a original answer.***
// Deliverables:
// - A listing of the specification and implementation files for UnsortedType
// - A listing of the driver program for your test plan
// - A listing of the test plan as input to the driver.
// - A listing of the output from the driver.
template
struct NodeType;
/* Assumption: ItemType is a type for which the operators
\"<\" and \"==\" are defined-either an appropriate built-in type or a
class that overloads these operators. */
template
class UnsortedType
{
public:
// Class constructor, destructor, and copy constructor
UnsortedType();
~UnsortedType();
UnsortedType(const UnsortedType&);
void operator=(UnsortedType);
bool IsFull() const;
// Determines whether list is full.
//Post: Function value = (list is full)
int GetLength() const;
// Determines the number of elements in list.
// Post: Function value = number of elements in list.
void RetrieveItem(ItemType& item, bool& found);
// Retrieves list element whose key matches item\'s key
// (if present).
// Pre: Key member of item is initialized.
// Post: If there is an element someItem whose key matches
// item\'s key, then found = true and item is a copy of
// someItem; otherwise found = false and item is unchanged.
// List is unchanged.
void InsertItem(ItemType item);
// Adds item to list.
// Pre: List is not full.
// Item is not in list.
// Post: item is in list.
void DeleteItem(ItemType item);
// Deletes the element whose key matches item\'s key
// Pre: Key member of item is initialized.
// One and only one element in list has a key matching
// item\'s key.
// Post: No element in list has a key matching item\'s key.
void ResetList();
// Initializes current position for an iteration through the list.
// Post: Current position is prior to list.
void GetNextItem(ItemType&);
// Gets the next element in list.
// Pre: Current position is defined.
// Element at current position is not last in list.
// Post: Current position is updated to next position.
// item is a copy of element at current position.
private:
NodeType* listData;
int length;
NodeType* currentPos;
};
Solution
#include
#include
/* structure for a node */
struct node
{
int data;
struct node *next;
};
/* function to insert a new_node in a list in sorted way.
Note that this function expects a pointer to head node
as this can modify the head of the input linked list */
void sortedInsert(struct node** head_ref, struct node* new_node)
{
struct node* current = *head_ref;
// Case 1 of the above algo
if (current == NULL)
{
new_node->next = new_node;
*head_ref = new_node;
}
// Case 2 of the above algo
else if (current->data >= new_node->data)
{
/* If value is smaller than head\'s value then
we need to change next of last node */
while(current->next != *head_ref)
current = current->next;
cur.
Using c++Im also using a the ide editor called CodeLiteThe hea.pdffashiongallery1
Typed out please In a short and simple response comment on this persons answer for masonry
work Additives combined with concrete to achieve certain properties are called what? Name a
few that would benefit the Engineer and Customer.
Response - Additives to concrete are utilized to provide certain benefits when placing concrete.
These additives called \"Admixtures\" can be used to speed up the curing process, slow down the
curing process, or help in working with concrete during cold temperatures. Retarders can be
added to concrete to slow down curing. Accelerators can be used to speed up the curing. The
most advanced additive is the Air-entrainment agent which gives mason the ability to work with
concrete in colder months.
Typed out please In a short and simple response comment on this persons answer for masonry
work Additives combined with concrete to achieve certain properties are called what? Name a
few that would benefit the Engineer and Customer.
Response - Additives to concrete are utilized to provide certain benefits when placing concrete.
These additives called \"Admixtures\" can be used to speed up the curing process, slow down the
curing process, or help in working with concrete during cold temperatures. Retarders can be
added to concrete to slow down curing. Accelerators can be used to speed up the curing. The
most advanced additive is the Air-entrainment agent which gives mason the ability to work with
concrete in colder months.
Response - Additives to concrete are utilized to provide certain benefits when placing concrete.
These additives called \"Admixtures\" can be used to speed up the curing process, slow down the
curing process, or help in working with concrete during cold temperatures. Retarders can be
added to concrete to slow down curing. Accelerators can be used to speed up the curing. The
most advanced additive is the Air-entrainment agent which gives mason the ability to work with
concrete in colder months.
Solution
The response of the person is good. He/she explained the admixtures and their applications pretty
well and also explained accelators, retarders and air entertainment in a simple straight forward
fashion.Overall i would say that the answer is satisfactory.
I will like to add \"PLASTICIZERS\" in the list of admixtures that would benefit the engineer
and customer. Plasticizers are water reducing admixtures and are added to the concrete mix for
making it more plastic without any further addition of water. In other words, they reduce the
quantity of water required to make concrete mixture of better plasticity.
PLEASE HIT LIKE BUTTON IF YOU FIND MY ANSWER SATISFACTORY.
THANK YOU..
Implement the sequence class from Section 3.2 of the textbook. The d.pdfinfo961251
Implement the sequence class from Section 3.2 of the textbook. The documentation and
definition portion of this sequence ADT is provided in textbook (pp.124-133), and is posted in
BlackBoard of this class too.
Also implement two operators + and += for the ADT. For the + operator, x+y (a new sequence)
contains all the items of x, followed by all the items of Y.
The statement x += y appends all of the items of y to the end of what’s already in X.
For simplicity, let’s assume the sequence contains integer items and the capacity is 30.
Write a simple application to manage a playlist of your favorite music, where the sequence class
is used to insert, delete, search and print the title of music.
Your application should read in integral numbers (an ID, instead of title, for simplicity) of each
piece of music and insert them onto a sequence. It should be able to insert an item at a specified
location, find and display the music currently at play, delete a specified item from the sequence
as well as display the entire list of music in the sequence.
// FILE: sequence1.h
// CLASS PROVIDED: sequence (part of the namespace main_savitch_3)
// There is no implementation file provided for this class since it is
// an exercise from Section 3.2 of \"Data Structures and Other Objects Using C++\"
//
// TYPEDEFS and MEMBER CONSTANTS for the sequence class:
// typedef ____ value_type
// sequence::value_type is the data type of the items in the sequence. It
// may be any of the C++ built-in types (int, char, etc.), or a class with a
// default constructor, an assignment operator, and a copy constructor.
//
// typedef ____ size_type
// sequence::size_type is the data type of any variable that keeps track of
// how many items are in a sequence.
//
// static const size_type CAPACITY = _____
// sequence::CAPACITY is the maximum number of items that a sequence can hold.
//
// CONSTRUCTOR for the sequence class:
// sequence( )
// Postcondition: The sequence has been initialized as an empty sequence.
//
// MODIFICATION MEMBER FUNCTIONS for the sequence class:
// void start( )
// Postcondition: The first item on the sequence becomes the current item
// (but if the sequence is empty, then there is no current item).
//
// void advance( )
// Precondition: is_item returns true.
// Postcondition: If the current item was already the last item in the
// sequence, then there is no longer any current item. Otherwise, the new
// current item is the item immediately after the original current item.
//
// void insert(const value_type& entry)
// Precondition: size( ) < CAPACITY.
// Postcondition: A new copy of entry has been inserted in the sequence
// before the current item. If there was no current item, then the new entry
// has been inserted at the front of the sequence. In either case, the newly
// inserted item is now the current item of the sequence.
//
// void attach(const value_type& entry)
// Precondition: size( ) < CAPACITY.
// Postcondition: A new copy of entry has been ins.
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.
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.
John, a sociologist, will be focusing on how larger societal institu.pdfpetercoiffeur18
John, a sociologist, will be focusing on how larger societal institutions play a role in drug usage
as well as the affects drug abuse has on individuals. John will be utilizing the: \'Micro-Macro
Continuum\'.
Select one:
True
False
Solution
True - Micro- macro Continuum
sociologist are concerned with from the smallest social realities to the largest trends and
developments in the social world.
Help to implement delete_node get_succ get_pred walk and.pdfcontact32
Help to implement delete_node, get_succ, get_pred, walk, and tree_search in the script
following the given structure:
#include "bst.h"
// ---------------------------------------
// Node class
// Default constructor
Node::Node() {
// TODO: Implement this
key = 0;
parent = nullptr;
left = nullptr;
right = nullptr;
}
// Constructor
Node::Node(int in) {
// TODO: Implement this
key = in;
parent = nullptr;
left = nullptr;
right = nullptr;
}
// Destructor
Node::~Node() {
// TODO: Implement this
delete left;
delete right;
}
// Add parent
void Node::add_parent(Node* in) {
// TODO: Implement this
parent = in;
}
// Add to left of current node
void Node::add_left(Node* in) {
// TODO: Implement this
left = in;
if (in != nullptr) {
in->add_parent(this);
}
}
// Add to right of current node
void Node::add_right(Node* in) {
// TODO: Implement this
right = in;
if (in != nullptr) {
in->add_parent(this);
}
}
// Get key
int Node::get_key()
{
// TODO: Implement this
return key;
}
// Get parent node
Node* Node::get_parent()
{
// TODO: Implement this
return parent;
}
// Get left node
Node* Node::get_left()
{
// TODO: Implement this
return left;
}
// Get right node
Node* Node::get_right()
{
// TODO: Implement this
return right;
}
// Print the key to ostream to
// Do not change this
void Node::print_info(ostream& to)
{
to << key << endl;
}
// ---------------------------------------
// ---------------------------------------
// BST class
// Walk the subtree from the given node
void BST::inorder_walk(Node* in, ostream& to)
{
// TODO: Implement this
if (in != nullptr) {
inorder_walk(in->get_left(), to);
in->print_info(to);
inorder_walk(in->get_right(), to);
}
}
// Constructor
BST::BST()
{
// TODO: Implement this
root = nullptr;
}
// Destructor
BST::~BST()
{
// TODO: Implement this
delete root;
}
// Insert a node to the subtree
void BST::insert_node(Node* in)
{
// TODO: Implement this
Node* curr = root;
Node* par = nullptr;
while (curr != nullptr) {
par = curr;
if (in->get_key() < curr->get_key()) {
curr = curr->get_left();
} else {
curr = curr->get_right();
}
}
in->add_parent(par);
if (par == nullptr) {
root = in;
} else if (in->get_key() < par->get_key()) {
par->add_left(in);
} else {
par->add_right(in);
}
}
// Delete a node to the subtree
void BST::delete_node(Node* out)
{
// TODO: Implement this
}
// minimum key in the BST
Node* BST::tree_min()
{
// TODO: Implement this
return get_min(root);
}
// maximum key in the BST
Node* BST::tree_max()
{
// TODO: Implement this
return get_max(root);
}
// Get the minimum node from the subtree of given node
Node* BST::get_min(Node* in)
{
// TODO: Implement this
if (in == nullptr) {
return nullptr;
}
while (in->get_left() != nullptr) {
in = in->get_left();
}
return in;
}
// Get the maximum node from the subtree of given node
Node* BST::get_max(Node* in)
{
// TODO: Implement this
if (in == nullptr) {
return nullptr;
}
while (in->get_right() != nullptr) {
in = in->get_right();
}
return in;
}
// Get successor of the given node
Node* BS.
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 ...
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.
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 .
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.
Java Foundations StackADT-java --- - Defines the interface to a stack.docxVictorXUQGloverl
Java Foundations
StackADT.java
/**
* Defines the interface to a stack collection.
*
* @author Java Foundations
* @version 4.0
*/
public interface StackADT<T> {
/**
* Adds the specified element to the top of this stack.
*
* @param element element to be pushed onto the stack
*/
public void push(T element);
/**
* Removes and returns the top element from this stack.
*
* @return the element removed from the stack
* @throws EmptyCollectionException if the stack is empty
*/
public T pop();
/**
* Returns the top element of this stack without removing it from the stack.
*
* @return the element on top of the stack. It is not removed from the stack
* @throws EmptyCollectionException if the stack is empty
*/
public T peek();
/**
* Returns true if this stack contains no elements.
*
* @return true if the stack is empty, false if the stack is not empty
*/
public boolean isEmpty();
/**
* Returns the number of elements in this stack.
*
* @return the number of elements in the stack
*/
public int size();
}
QueueADT.java
/**
* QueueADT defines the interface to a queue collection.
*
* @author Java Foundation
* @version 4.0
*/
public interface QueueADT<T> {
/**
* Adds one element to the rear of this queue.
*
* @param element the element to be added to the rear of the queue
*/
public void enqueue(T element);
/**
* Removes and returns the element at the front of this queue.
*
* @return the element at the front of the queue
* @throws EmptyCollectionException if the queue is empty
*/
public T dequeue();
/**
* Returns without removing the element at the front of this queue.
*
* @return the first element in the queue
* @throws EmptyCollectionException if the queue is empty
*/
public T first();
/**
* Returns true if this queue contains no elements.
*
* @return true if the queue is empty, false if the queue is not empty
*/
public boolean isEmpty();
/**
* Returns the number of elements in this queue.
*
* @return the number of elements in the queue
*/
public int size();
}
LinkedDeque.java
public class LinkedDeque<T> implements QueueADT<T>, StackADT<T>, DequeADT<T> {
// inner class for a double linked list node
private class DNode<T> {
private T element;
private DNode<T> prev, next;
}
// data fields for the LinkedDeque class
private DNode<T> front, rear;
private int size;
// deque interface methods
@Override
public void addFirst(T element) {
// create a new node and set it up
DNode<T> newNode = new DNode<T>();
newNode.element = element; // from param to new node obj
newNode.prev = newNode.next = null;
if(this.isEmpty()) {
// we are making the only node in the deque
this.rear = this.front = newNode;
} else {
// there already exists a new node
// so, put the new node before the front node
newNode.next = this.front;
this.front.prev = newNode;
this.front = newNode;
}
this.size++;
}
@Override
public T removeFirst() {
T grabbedElt = this.getFirst(); // checks for empty for us
if.
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 .
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.
Using NetBeansImplement a queue named QueueLL using a Linked List .pdfsiennatimbok52331
Using NetBeans
Implement a queue named QueueLL using a Linked List (same as we did for the stack). This
implementation must be used in all the following problems.
Implement a queue QueueST using a stack (use StackLL).
Test your implementations in the main with examples.
Solution
Answer:-
import java.util.*;
/* Class Node */
class Node
{
protected int data;
protected Node link;
/* Constructor */
public Node()
{
link = null;
data = 0;
}
/* Constructor */
public Node(int d,Node n)
{
data = d;
link = n;
}
/* Function to set link to next Node */
public void setLink(Node n)
{
link = n;
}
/* Function to set data to current Node */
public void setData(int d)
{
data = d;
}
/* Function to get link to next node */
public Node getLink()
{
return link;
}
/* Function to get data from current Node */
public int getData()
{
return data;
}
}
/* Class linkedQueue */
class linkedQueue
{
protected Node front, rear;
public int size;
/* Constructor */
public linkedQueue()
{
front = null;
rear = null;
size = 0;
}
/* Function to check if queue is empty */
public boolean isEmpty()
{
return front == null;
}
/* Function to get the size of the queue */
public int getSize()
{
return size;
}
/* Function to insert an element to the queue */
public void insert(int data)
{
Node nptr = new Node(data, null);
if (rear == null)
{
front = nptr;
rear = nptr;
}
else
{
rear.setLink(nptr);
rear = rear.getLink();
}
size++ ;
}
/* Function to remove front element from the queue */
public int remove()
{
if (isEmpty() )
throw new NoSuchElementException(\"Underflow Exception\");
Node ptr = front;
front = ptr.getLink();
if (front == null)
rear = null;
size-- ;
return ptr.getData();
}
/* Function to check the front element of the queue */
public int peek()
{
if (isEmpty() )
throw new NoSuchElementException(\"Underflow Exception\");
return front.getData();
}
/* Function to display the status of the queue */
public void display()
{
System.out.print(\"\ Queue = \");
if (size == 0)
{
System.out.print(\"Empty\ \");
return ;
}
Node ptr = front;
while (ptr != rear.getLink() )
{
System.out.print(ptr.getData()+\" \");
ptr = ptr.getLink();
}
System.out.println();
}
}
/* Class LinkedQueueImplement */
public class LinkedQueueImplement
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
/* Creating object of class linkedQueue */
linkedQueue lq = new linkedQueue();
/* Perform Queue Operations */
System.out.println(\"Linked Queue Test\ \");
char ch;
do
{
System.out.println(\"\ Queue Operations\");
System.out.println(\"1. insert\");
System.out.println(\"2. remove\");
System.out.println(\"3. peek\");
System.out.println(\"4. check empty\");
System.out.println(\"5. size\");
int choice = scan.nextInt();
switch (choice)
{
case 1 :
System.out.println(\"Enter integer element to insert\");
lq.insert( scan.nextInt() );
break;
case 2 :
try
{
System.out.println(\"Removed Element = \"+ lq.remove());
}
catch (Exception e)
{
System.out.println(\"Error : \" + e.getMessage());
}
break;
case 3 .
For this project, write a program that stores integers in a binary.docxbudbarber38650
For this project, write a program that stores integers in a binary search tree.
The tree should use the BTNode class which is provided.
Write a test program that generates 20 random numbers in the range of -50 to 50 to build the tree and then uses preorderPrint,
inorderPrint, and postOrderPrint to display the contents of the tree.
To get an A implement a new method for the BTNode class which creates a Java vector class to contain
the data from all the nodes in the tree. The specification for this method is provided in the BTNode file.
Details about the Java vector class are provided in Appendix D, although the only vector method you'll use is addElement.
Also specify and implement in-order and post-order traversals and answer the question which of the
three new methods creates a vector with the entries sorted from smallest to largest?
Your test program should display the vectors created by your new methods rather than the print methods of BTNode.
// File: BTNode.java from the package edu.colorado.nodes
// Complete documentation is available from the BTNode link in:
// http://www.cs.colorado.edu/~main/docs/
package BTNode;
import java.util.Vector;
/******************************************************************************
* A <CODE>BTNode<<E></CODE> provides a node for a binary tree. Each node
* contains a piece of data (which is a reference to an E object) and references
* to a left and right child. The references to children may be null to indicate
* that there is no child. The reference stored in a node can also be null.
*
* <dl><dt><b>Limitations:</b> <dd>
* Beyond <CODE>Int.MAX_VALUE</CODE> elements, <CODE>treeSize</CODE>, is
* wrong.
*
* <dt><b>Java Source Code for this class:</b><dd>
* <A HREF="../../../../edu/colorado/nodes/BTNode.java">
* http://www.cs.colorado.edu/~main/edu/colorado/nodes/BTNode.java </A>
*
* @author Michael Main
* <A HREF="mailto:[email protected]"> ([email protected]) </A>
*
* @version
* Jul 22, 2005
******************************************************************************/
public class BTNode<E>
{
// Invariant of the BTNode<E> class:
// 1. Each node has one reference to an E Object, stored in the instance
// variable data.
// 2. The instance variables left and right are references to the node's
// left and right children.
private E data;
private BTNode<E> left, right;
/**
* Initialize a <CODE>BTNode</CODE> with a specified initial data and links
* children. Note that a child link may be the null reference,
* which indicates that the new node does not have that child.
* @param <CODE>initialData</CODE>
* the initial data of this new node
* @param <CODE>initialLeft</CODE>
* a reference to the left child of this new node--this reference may be null
* to indicate that there is no node after this new node.
* @param <CODE>initialRight</CODE>
.
Please fix my errors class Iterator public Construc.pdfkitty811
Please fix my errors
class Iterator
{
public:
/// Constructor taking a head and tail pointer; YOU'RE WELCOME
Iterator(Node<T> *head, Node<T> *tail) : head_(head), tail_(tail)
{
cursor_ = end();
}
/// Constructor taking a head, tail, and cursor pointer; YOU'RE WELCOME
Iterator(Node<T> *head, Node<T> *tail, Node<T> *cursor) : head_(head), tail_(tail),
cursor_(cursor) {}
/// Get a pointer to the head node, or end() if this list is empty
Node<T> *begin() { return head_; }
/// Get a node pointer representing "end" (aka "depleted"). Probably want to just use nullptr.
Node<T> *end() { return nullptr; }
/// Get the node to which this iterator is currently pointing
Node<T> *getCursor() { return cursor_; }
/**
* Assignment operator
* Return a copy of this Iterator, after modification
*/
Iterator &operator=(const Iterator &other)
{
head_ = other.head_;
tail_ = other.tail_;
cursor_ = other.cursor_;
return *this;
}
/**
* Comparison operator
* Returns true if this iterator is equal to the other iterator, false otherwise
*/
bool operator==(const Iterator &other)
{
return cursor_ == other.cursor_;
}
/**
* Inequality comparison operator
* Returns true if this iterator is not equal to the other iterator, false otherwise
*/
bool operator!=(const Iterator &other)
{
return !(*this == other);
}
/**
* Prefix increment operator
* Return a copy of this Iterator, after modification
*/
Iterator &operator++()
{
cursor_ = cursor_->getNext();
return *this;
}
/*** Postfix increment
* Return a copy of this Iterator, BEFORE it was modified
*/
Iterator operator++(int)
{
Iterator copy(*this);
++(*this);
return copy;
}
/*** Prefix decrement operator
* Return a copy of this Iterator, after modification
*/
Iterator &operator--()
{
cursor_ = cursor_->getPrev();
return *this;
}
/**
* Postfix decrement operator
* Return a copy of this Iterator BEFORE it was modified
*/
Iterator operator--(int)
{
Iterator copy = *this;
--(*this);
return copy;
}
/**
* AdditionAssignment operator
* Return a copy of the current iterator, after modification
*/
Iterator operator+=(size_t add)
{
for (size_t i = 0; i < add && cursor_ != nullptr; ++i)
{
cursor_ = cursor_->getNext();
}
return *this;
}
/**
* SubtractionAssignment operator
* Return a copy of the current iterator, after modification
*/
Iterator operator-=(size_t sub)
{
for (size_t i = 0; i < sub && cursor_ != nullptr; ++i)
{
cursor_ = cursor_->getPrev();
}
return *this;
}
/**
* AdditionAssignment operator, supporting positive or negative ints
*/
Iterator operator+=(int add)
{
if (add > 0)
{
for (int i = 0; i < add && cursor_ != nullptr; ++i)
{
cursor_ = cursor_->getNext();
}
}
else
{
for (int i = 0; i > add && cursor_->getPrev() != nullptr; --i)
{
cursor_ = cursor_->getPrev();
}
}
return *this;
}
/**
* SubtractionAssignment operator, supporting positive or negative ints
*/
Iterator operator-=(int subtract)
{
// This function adds an integer to the current iterators position in the list,
if (subtract > 0)
{
for (int i = 0; i < subtract && cursor_.
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 ...
(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.
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(.
Implement the following specification of UnsortedType using circular.pdfudit652068
Implement the following specification of UnsortedType using circular linked list as the
implementation structure.
*** I have seen this question answered here before but it is not a good answer. Can someone
please give me a original answer.***
// Deliverables:
// - A listing of the specification and implementation files for UnsortedType
// - A listing of the driver program for your test plan
// - A listing of the test plan as input to the driver.
// - A listing of the output from the driver.
template
struct NodeType;
/* Assumption: ItemType is a type for which the operators
\"<\" and \"==\" are defined-either an appropriate built-in type or a
class that overloads these operators. */
template
class UnsortedType
{
public:
// Class constructor, destructor, and copy constructor
UnsortedType();
~UnsortedType();
UnsortedType(const UnsortedType&);
void operator=(UnsortedType);
bool IsFull() const;
// Determines whether list is full.
//Post: Function value = (list is full)
int GetLength() const;
// Determines the number of elements in list.
// Post: Function value = number of elements in list.
void RetrieveItem(ItemType& item, bool& found);
// Retrieves list element whose key matches item\'s key
// (if present).
// Pre: Key member of item is initialized.
// Post: If there is an element someItem whose key matches
// item\'s key, then found = true and item is a copy of
// someItem; otherwise found = false and item is unchanged.
// List is unchanged.
void InsertItem(ItemType item);
// Adds item to list.
// Pre: List is not full.
// Item is not in list.
// Post: item is in list.
void DeleteItem(ItemType item);
// Deletes the element whose key matches item\'s key
// Pre: Key member of item is initialized.
// One and only one element in list has a key matching
// item\'s key.
// Post: No element in list has a key matching item\'s key.
void ResetList();
// Initializes current position for an iteration through the list.
// Post: Current position is prior to list.
void GetNextItem(ItemType&);
// Gets the next element in list.
// Pre: Current position is defined.
// Element at current position is not last in list.
// Post: Current position is updated to next position.
// item is a copy of element at current position.
private:
NodeType* listData;
int length;
NodeType* currentPos;
};
Solution
#include
#include
/* structure for a node */
struct node
{
int data;
struct node *next;
};
/* function to insert a new_node in a list in sorted way.
Note that this function expects a pointer to head node
as this can modify the head of the input linked list */
void sortedInsert(struct node** head_ref, struct node* new_node)
{
struct node* current = *head_ref;
// Case 1 of the above algo
if (current == NULL)
{
new_node->next = new_node;
*head_ref = new_node;
}
// Case 2 of the above algo
else if (current->data >= new_node->data)
{
/* If value is smaller than head\'s value then
we need to change next of last node */
while(current->next != *head_ref)
current = current->next;
cur.
Using c++Im also using a the ide editor called CodeLiteThe hea.pdffashiongallery1
Typed out please In a short and simple response comment on this persons answer for masonry
work Additives combined with concrete to achieve certain properties are called what? Name a
few that would benefit the Engineer and Customer.
Response - Additives to concrete are utilized to provide certain benefits when placing concrete.
These additives called \"Admixtures\" can be used to speed up the curing process, slow down the
curing process, or help in working with concrete during cold temperatures. Retarders can be
added to concrete to slow down curing. Accelerators can be used to speed up the curing. The
most advanced additive is the Air-entrainment agent which gives mason the ability to work with
concrete in colder months.
Typed out please In a short and simple response comment on this persons answer for masonry
work Additives combined with concrete to achieve certain properties are called what? Name a
few that would benefit the Engineer and Customer.
Response - Additives to concrete are utilized to provide certain benefits when placing concrete.
These additives called \"Admixtures\" can be used to speed up the curing process, slow down the
curing process, or help in working with concrete during cold temperatures. Retarders can be
added to concrete to slow down curing. Accelerators can be used to speed up the curing. The
most advanced additive is the Air-entrainment agent which gives mason the ability to work with
concrete in colder months.
Response - Additives to concrete are utilized to provide certain benefits when placing concrete.
These additives called \"Admixtures\" can be used to speed up the curing process, slow down the
curing process, or help in working with concrete during cold temperatures. Retarders can be
added to concrete to slow down curing. Accelerators can be used to speed up the curing. The
most advanced additive is the Air-entrainment agent which gives mason the ability to work with
concrete in colder months.
Solution
The response of the person is good. He/she explained the admixtures and their applications pretty
well and also explained accelators, retarders and air entertainment in a simple straight forward
fashion.Overall i would say that the answer is satisfactory.
I will like to add \"PLASTICIZERS\" in the list of admixtures that would benefit the engineer
and customer. Plasticizers are water reducing admixtures and are added to the concrete mix for
making it more plastic without any further addition of water. In other words, they reduce the
quantity of water required to make concrete mixture of better plasticity.
PLEASE HIT LIKE BUTTON IF YOU FIND MY ANSWER SATISFACTORY.
THANK YOU..
Implement the sequence class from Section 3.2 of the textbook. The d.pdfinfo961251
Implement the sequence class from Section 3.2 of the textbook. The documentation and
definition portion of this sequence ADT is provided in textbook (pp.124-133), and is posted in
BlackBoard of this class too.
Also implement two operators + and += for the ADT. For the + operator, x+y (a new sequence)
contains all the items of x, followed by all the items of Y.
The statement x += y appends all of the items of y to the end of what’s already in X.
For simplicity, let’s assume the sequence contains integer items and the capacity is 30.
Write a simple application to manage a playlist of your favorite music, where the sequence class
is used to insert, delete, search and print the title of music.
Your application should read in integral numbers (an ID, instead of title, for simplicity) of each
piece of music and insert them onto a sequence. It should be able to insert an item at a specified
location, find and display the music currently at play, delete a specified item from the sequence
as well as display the entire list of music in the sequence.
// FILE: sequence1.h
// CLASS PROVIDED: sequence (part of the namespace main_savitch_3)
// There is no implementation file provided for this class since it is
// an exercise from Section 3.2 of \"Data Structures and Other Objects Using C++\"
//
// TYPEDEFS and MEMBER CONSTANTS for the sequence class:
// typedef ____ value_type
// sequence::value_type is the data type of the items in the sequence. It
// may be any of the C++ built-in types (int, char, etc.), or a class with a
// default constructor, an assignment operator, and a copy constructor.
//
// typedef ____ size_type
// sequence::size_type is the data type of any variable that keeps track of
// how many items are in a sequence.
//
// static const size_type CAPACITY = _____
// sequence::CAPACITY is the maximum number of items that a sequence can hold.
//
// CONSTRUCTOR for the sequence class:
// sequence( )
// Postcondition: The sequence has been initialized as an empty sequence.
//
// MODIFICATION MEMBER FUNCTIONS for the sequence class:
// void start( )
// Postcondition: The first item on the sequence becomes the current item
// (but if the sequence is empty, then there is no current item).
//
// void advance( )
// Precondition: is_item returns true.
// Postcondition: If the current item was already the last item in the
// sequence, then there is no longer any current item. Otherwise, the new
// current item is the item immediately after the original current item.
//
// void insert(const value_type& entry)
// Precondition: size( ) < CAPACITY.
// Postcondition: A new copy of entry has been inserted in the sequence
// before the current item. If there was no current item, then the new entry
// has been inserted at the front of the sequence. In either case, the newly
// inserted item is now the current item of the sequence.
//
// void attach(const value_type& entry)
// Precondition: size( ) < CAPACITY.
// Postcondition: A new copy of entry has been ins.
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.
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.
Similar to 1)(JAVA) Extend the Binary Search Tree ADT to include a public metho.pdf (20)
John, a sociologist, will be focusing on how larger societal institu.pdfpetercoiffeur18
John, a sociologist, will be focusing on how larger societal institutions play a role in drug usage
as well as the affects drug abuse has on individuals. John will be utilizing the: \'Micro-Macro
Continuum\'.
Select one:
True
False
Solution
True - Micro- macro Continuum
sociologist are concerned with from the smallest social realities to the largest trends and
developments in the social world.
In what ways do humans effect the environment Explain in 200 words.pdfpetercoiffeur18
In what ways do humans effect the environment? Explain in 200 words
Solution
Human activities have serious effects on the environment. The human civilization so far has
imposed a high cost on the environment. For example, increase in population led to deforestation
to increase suitable lands for human inhabitation. Also, increased population led to increased
need for food, which led to further deforestation for agricultural activities. Industrial activities
and mining also lead to deforestation. Human inhabitation and industrial activities lead to
diversion of the rivers, extensive mining activities, drilling on the earth surface to extract oil, etc.
Diversion of the rivers might lead to drought or flood in various areas. Human activities also
result in erosion of soil.
Industrial activities have resulted in rising temperature, which has caused changing weather
pattern, behavior in the sea wave, pattern and amount in rainfall, etc. Human activities have
increased accumulation of carbon-di-oxide and other greenhouse gases in the environment,
which has increased the average temperature. Such an increase in temperature has created a
potential situation in which the polar ice can melt and result in the destruction of various cities
near seas. Also, human activities have resulted in a breach in the ozone layer which has resulted
in dangerous UV rays to penetrate the ozone layer. Therefore, human activities have significantly
affected the environment..
i need a taking turn method for a player vs computer battleship game.pdfpetercoiffeur18
i need a taking turn method for a player vs computer battleship game in java. when a user slects
on players board then computer should be able to pick one on the computer board. this should
continue to repeat the order until the first one finds all the ship on their board first.
Solution
import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.border.*;
import java.io.*; import java.lang.Integer; import java.util.Vector; import java.net.*; public class
Battleship extends JFrame { private static JButton ok = new
JButton(\"OK\"),//closes stats menu done =new
JButton(\"Done\");//closes options menu private static JFrame statistics= new
JFrame(\"Statistics\"),//holds stats options=new
JFrame(\"Options\");//holds opts private static JLabel data,//used for stats menu
title;//used for options menu private static JPanel stats=new
JPanel(),//used for stats menu opts,//used for options menu
inputpanel;//for manually inputting ships private static Container
b,c,d;//board and input panel private JPanel input;//input bar private static
JMenuItem m,pvp,pvc,cvc;//menu items private static String[] cletters = {\"
\",\"A\",\"B\",\"C\",\"D\",\"E\",\"F\",\"G\",\"H\",\"I\",\"J\"}, //array of letters used for combo
boxes cnumbers = {\"
\",\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"10\"}, //array of numbers used for
combo boxes ships =
{\"Carrier\",\"Battleship\",\"Submarine\",\"Destroyer\", \"Patrol
Boat\"},//strings used for ship combo box direction =
{\"Horizontal\",\"Vertical\"},//directions level={\"Normal\",
\"Ridiculously Hard\"}, layout={\"Manual\",\"Automatic\"},
colors={\"Cyan\", \"Green\", \"Yellow\", \"Magenta\", \"Pink\", \"Red\",
\"White\"}, first={\"Player 1\", \"Player 2\",
\"Random\"};//used for options private JComboBox cshi = new JComboBox(ships),//ships
cdir = new JComboBox(direction);//directions private static
JComboBox aiLevel=new JComboBox(level), shipLayout=new
JComboBox(layout), shipColor=new JComboBox(colors),
playsFirst=new JComboBox(first);//used
//for options menu private JTextField mbar = new JTextField();//message bar
private static int enemy=1, i,j,//counters
length=5, you=0,
prevcolor=0,//index of previous color prevFirst=0,
prevLayout=0, prevLevel=0,//tracks changes in corresponding comboboxes
ready=0, sindex=0,//stores index of array
dindex=0;//direction private static Player players[]=new Player[2]; private static
JButton deploy=new JButton(\"DEPLOY\"); private static int
w=0,a=0,s=0,t=0,e=0;//counters to track the use of all ships private static String[][]
shiphit=new String[10][10]; private static String user,user2; private static Color[]
color={Color.cyan,Color.green,Color.yellow,Color.magenta,
Color.pink, Color.red, Color.white}; private static Object
selectedValue=\" \", gametype; private static
BattleshipClient me; private static boolean gameover=false; public Battleship()
{ setTitle(\"Battleship\");
setDefaultCloseOperation(EXIT_ON_CLOSE); setJMenuBar(createMenuBar());
setResizabl.
I am trying to change this code from STRUCTS to CLASSES, the members.pdfpetercoiffeur18
I am trying to change this code from STRUCTS to CLASSES, the members have to be private.
Well, I think I did a semi-ok job; the code doesn\'t run and I have no idea why. Can you please
help. Platform: C++
========== C++ CODE ============
#include
#include
#include
#include
#include //must have to use system (\"pause\" );
//#include \"personType.h\"
using namespace std;
const int MAX_EMPLOYEES = 50;
//----------------------------------
class employeeType{ //:public personType
private:
long empID;
string first;
string last;
char gender;
double payrate;
string jobRole;
int years;
public:
virtual void programmer_info() const=0;
//Function to output employee\'s data
virtual double cutBacks(employeeType let[], int listsize) const=0;
//Function to calculate and return the wages.
//Postcondition: Pay is calculated and returned
void yourFired(employeeType let[], int& listsize , long id); //int& cuz we are restando
cantidades de la lista.
//Function to set the salary. /Postcondition: personId = id
long seqSearch(employeeType let[], int listLength, int searchItem)const;
//Function to retrieve the id. /Postcondition: returns personID
employeeType (long id = 0, string first = \"\", string last = \"\", char gender = \"\",
double payrate = 0, string jobRole = \"\",int years = 0);
//Ibefore it was: userinput();
//Constructor with parameters //Sets the first name, last name, payRate, and
//hoursWorked according to the parameters. If no value is specified, the default
//values are assumed. //Postcondition: firstName = first;
///==============================================================
void getData(ifstream& inFile, class employeeType let[], int& listSize);
void printOne ( employeeType one);
void hireOne(employeeType let[], int& listsize); //int& cuz we are adding or restyando
cantidades de la lista.
void selectionSort( employeeType let[], int length);
void printList(employeeType let[], int listSize);
employeeType getOne ( ifstream& dataIn );
};
///===============================================================
void employeeType::yourFired(long id)
{
empID = id;
}
long employeeType::seqSearch() const
{
return empID;
}
employeeType::employeeType(long id, string first, string last, char gender,
double, string jobRole,int years)
: personType(first, last)
{
empID = id;
}
//----------------------------------
int main ()
{
int number; // number of employees in the file
int id;
char choice;
class employeeType [MAX_EMPLOYEES], newrecord;
ifstream dataFile;
dataFile.open ( \"newEmployees.txt\");
if (!dataFile){
cout << \"\ Error with input file!!\ \ \";
//system (\"pause\"); // must #include
return 1;
}
getData (dataFile, employeeType, number);
cout < to be used
/// TASK 3 =======================================================
for(int i =0; i<3 ; i++){ //calling hireOne 3 times, you can insert 3 new employees on a roll
hireOne(employeeType, number); // the list increases by up to 3 new records each time
}
cout << \"After hiring employees, new list: \ \"<> id;
your.
how internal resources and capabilities can be a source of sustainab.pdfpetercoiffeur18
how internal resources and capabilities can be a source of sustainable competitive advantage for
a company
Solution
Ans:- Internal analysis is the process of identifying and evaluating an organization’s specific
characteristics, including its:
An internal analysis is comprised of looking at the following elements:
Resources are the assets that an organization has for carrying out whatever work activities and
processes relative to its business definition, business mission, and goals and objectives.
Commonly, these resources are as follows:
Organizational resources must be processed or used in some way to get value out of them. The
various resources are the inputs for organizational capabilities. Organizational capabilities are the
complex and coordinated network of organizational routines and processes that determine how
efficiently and effectively the organization transforms its inputs (resources) into outputs
(products and/or services).
Sustainable competitive advantage is the prolonged maintenance of competitive advantage.
Capabilities that lead to a competitive advantage today may not continue to do so as market
conditions and competitors change. Dynamic (flexible) capabilities are an organization’s ability
to build, integrate, and reconfigure capabilities to address rapidly environmental changes (shifts).
Distinctive organizational capabilities are the extraordinary and unique capabilities that
distinguish the organization from its competitors. They allow the organization to develop a
sustainable competitive advantage to outperform its competition.
Three characteristics that make a capability distinctive are as follows:
Core competencies are the organization’s major value-creating skills and capabilities that are
shared across multiple product lines or multiple businesses. This internal sharing process is what
distinguishes core competencies from distinctive capabilities.
The relationship between organizational capabilities, distinctive organizational capabilities, and
core competencies are as follows:
Competitive advantage is what sets an organization apart. Without a sustainable competitive
advantage, the organization’s long-run success and survival are uncertain.
The aggregate reason for doing an internal analysis is to assess what the organization has or does
not have and what it can and cannot do—in other words, its strengths and its weaknesses.
Strengths are resources that the organization possesses and capabilities that the organization has
developed, both of which can be exploited and developed into sustainable competitive
advantage. Not all strengths have the potential to be a sustainable competitive advantage..
For an organism that is growing using glucose as the electron donor, .pdfpetercoiffeur18
For an organism that is growing using glucose as the electron donor, name at least one electron
acceptor that the organism could use for each of the following metabolic pathways: For aerobic
respiration, cells could use __ For anaerobic respiration, cells could use: __ For fermentation,
cells could use:
Solution
A.For aerobic respiration,cells could use:Oxygen
B.For anaerobic respiration,cells could use:Sulfate,nitrate or sulfur.
C.For fermentation,cells could use:Acetaldehyde in alcohol fermentation and pyruvate in lactic
acid fermentation..
Exercise 5.6.28. For each of the following descriptions of a function.pdfpetercoiffeur18
Exercise 5.6.28. For each of the following descriptions of a function f, find a suh S of the
domain of f such that the restriction fIs is a bijection onto the range of f. (a)f : N N, wheref(n)-n
+ 1 if n is odd and/(n) =n/2 if n is even (b)f : R Z, wheref(x)- . Here lxl denotes the floor\' or.
(c)f : R R, where,f(x) =x3-3x2 , (d)f : R R, where,f(x) =x4-4x2 (e)f : R R, wheref(x)=xe-x. ,
find a subset 7 The floor function from R to Z assigns to each x R the greatest integer less than or
equal to x. It is denoted by Lx. For example, L = 3 and L-r=-4 ie, | | = 3
Solution
A bijective function is a one to one function that is form every x value there will be exactly one y
value.
In simopler terms each element in the domain set of a function when plugged in the function
gives a distinct value of the function
that is a part of the range of the function.
in our problem we need to find the subset of a domain for which the function is bijective
a> f : N-->N , f(n) = n+1
the domain and the range are all natural numbers
that is n E [0,1,2,3,4,.....N]
if n is odd
f(n)= n+1 ,this is a straight line and this function will be bijective for all odd natural numbers that
is n E (2k+1) will be the
domain in which f(n) will be bijective ,as for all odd values of n we\'ll get distinct f values.
n E [1 , 2k+1] , here k = 1,2,3........k just the integral vaslues
when n is even
f(n) = n/2 , this again is a straight line so the domain in whicj f(n) is bijective will be all even
natural, numbers\\that is
n E 2k ,k E {1,2,3,4...N}
b> f(x) = [x]
x : Z-->Z
here f(x) represents a step function
and a step function have the same range for all the x values within a particular step domain
so f(x) = [x] , cannot be a one to one function as we do not get distinct f(x) values for different x
values
c> f(x) = x^3-3x^2
f(x)= x^2(x-3)
this function will be a curve with zeros at x = 0 and 3
and it will not be a bijective or one to one function over the entire real number line.
d>
f(x) = x^4-4x^2
this function will be a curve with zeros at x = 0 and 2 and -2
and it will not be a bijective or one to one function over the entire real number line..
Discuss concepts associated with mercantilism demonstrating key poli.pdfpetercoiffeur18
Discuss concepts associated with mercantilism demonstrating key policies that a country would
implement if they were to apply such a theory. What is the liberal critique of mercantilism?
Solution
It was counterpart of political nationalism and argued for it. It exhibited aspirations of rising
merchant capitalists to whom strong state appeared necessary for their own protection. Abundant
money supply was necessary for them. IT AIMED AT STATE POWER AND UNIFICATION
OF COUNTRY. WEALTH OF NATIONS INTERESTED THEM. IT ARGUED FOR
ENHANCEMENT OF STATE POWER THROUGH ECONOMIC MEANS. THIS WAS
ACHIEVED FROM WEALTH AND ECONOMIC POWER OF NATION. WEALTH IN
ABSENCE OF MINES COULD BE ACHIEVED THROUGH BALANCE OF PAYMENT
SURPLUS. NATION MUST HAVE WELL EQUIPPED ARMY AND NAVY TO DEFEND
ITSELF AND TO PROTECT ITS INTERESTS IN OUTER WORLD. THEY EQUATED
MONEY WITH WEALTH AND FOR THEM ONLY WAY TO ACQUIRE SPECIE WAS
THROUGH BOP SURPLUS.. THEY VIEWED MONEY SUPPLY AS WORKING CAPITAL
FOR TRADING ACTIVITIES. THEY VIEWED FALLING PRICES UNFAVOURABLY AND
ACCORDING TO THEM RISING PRICES WERE STIMULATING TO INDUSTRY.
ACCORDING TO THEM STATE SHOULD HELP FOR FAVOURABLE Bop.
From the proceeding discussion it is clear mercantalists will argue for govt intervention in
economy. Other policy conclusions will be strong govt and army, acquisition of colonies,
maximum exports and minimum imports to achieve bop surplus, mercantalism proper also
argued for such imports (rawmaterials) which led to exports of greater value, Rising prices and
profits etc
The liberals argued that beggar thy neighbour attitude will harm even our own country. They
argued for trade based on comparative and absolute advantage which benefits every country.
They are against state intervention prescribed by mercantalists and believe in laissez-faire. For
them rising prices are harmful..
C++ Caesar Cipher project. Write your codes for the following functi.pdfpetercoiffeur18
C++ Caesar Cipher project. Write your codes for the following functions using the shift cipher:
Encrypt: INPUT: plaintext, key OUTPUT: ciphertext
Decrypt: INPUT: ciphertext, key OUTPUT: plaintext
Solution
Tested on windows os with dev cpp
/*****************caesar.cpp*******************/
#include
using namespace std;
int shift=6;
// This function receives text and shift and
// returns the encrypted text
string encrypt(string text)
{
string result = \"\";
// traverse text
for (int i=0;i
using namespace std;
// This function receives text and shift and
// returns the plain text
string decrypt(string text)
{
string result = \"\";
// traverse text
for (int i=0;i.
any idea#includeiostream using stdcout; using stdendl; .pdfpetercoiffeur18
any idea?
#include
using std::cout; using std::endl;
using std::ostream; using std::cin; using std::boolalpha;
#include
using std::copy; using std::sort;
#include
using std::swap;
#include
using std::string;
#include
using std::vector;
#include
using std::distance; using std::istream_iterator;
using std::back_inserter;
#include
using std::ostringstream;
// ADD MORE INCLUDES if you need them to the above
template
struct SetElement{
public:
T element;
int cnt;
SetElement()=default;
SetElement(T val);
};
// FIX BELOW for SetElement!!!
// The T val constructor and operator<< below here for SetElement
template
SetElement::SetElement(T val){
cnt = 1;
element = val;
}
template
ostream &operator<<(ostream os, const SetElement& p){
os<
class MSet{
private:
SetElement* ary_;
size_t size_;
size_t capacity_;
void grow();
public:
MSet(size_t s=2);
MSet(T val);
MSet(vector&);
MSet(MSet&);
MSet operator=(MSet);
~MSet();
size_t size();
size_t capacity();
SetElement* find(T);
void insert(T);
size_t count(T val);
bool erase(T);
friend ostream& operator<<(ostream& out, MSet& m){
// FIX THIS RIGHT HERE. ENTER YOUR CODE HERE
out<<\"test\";
return out;
};
};
// MANY THINGS BELOW HERE FOR MSet
template
MSet::MSet(size_t s){
ary_ = new T[s]();
}
/*
template
size_t MSet::size_(){
cout <<\"test\"<< endl;
return size_t;
}
*/
// DO NOT CHANGE ANYTHING BELOW. TESTING!
int main(){
int test;
long l1, l2, l3;
cin >> test;
cout << boolalpha;
switch (test){
// basic constructors, .size() and .capacity()
case 1 : {
MSet m_l;
/*
cout << m_l.size() <<\":\"<< m_l.capacity()<> l1;
MSet m_l_oneval(l1);
cout << m_l_oneval.size() <<\":\"<< m_l_oneval.capacity()<
Solution
your mistack is:
ary_ = new SetElement[s]; is correct.
not ary_ = new T[s]();
Program:
#include
using std::cout; using std::endl;
using std::ostream; using std::cin; using std::boolalpha;
#include
using std::copy; using std::sort;
#include
using std::swap;
#include
using std::string;
#include
using std::vector;
#include
using std::distance; using std::istream_iterator;
using std::back_inserter;
#include
using std::ostringstream;
// ADD MORE INCLUDES if you need them to the above
template
struct SetElement{
public:
T element;
int cnt;
SetElement()=default;
SetElement(T val);
};
// FIX BELOW for SetElement!!!
// The T val constructor and operator<< below here for SetElement
template
SetElement::SetElement(T val){
cnt = 1;
element = val;
}
template
ostream &operator<<(ostream os, const SetElement& p){
os<
class MSet{
private:
SetElement* ary_;
size_t size_;
size_t capacity_;
void grow();
public:
MSet(size_t s=2);
MSet(T val);
MSet(vector&);
MSet(MSet&);
MSet operator=(MSet);
~MSet();
size_t size();
size_t capacity();
SetElement* find(T);
void insert(T);
size_t count(T val);
bool erase(T);
friend ostream& operator<<(ostream& out, MSet& m){
// FIX THIS RIGHT HERE. ENTER YOUR CODE HERE
out<<\"test\";
return out;
};
};
// MANY THINGS BELOW HERE FOR MSet
template
MSet::MSet(size_t s){
ary_ = new SetElement[s];
}
/*
template
.
a) Use Newton’s Polynomials for Evenly Spaced data to derive the O(h.pdfpetercoiffeur18
a) Use Newton’s Polynomials for Evenly Spaced data to derive the O(h4) accurate Second
Centered Difference approximation of the 1st derivative at nx. Start with a polynomial fit to
points at n-2x , n-1x, nx , n+1x and n+2x .
b) Use Newton’s Polynomials for Evenly Spaced data to derive the O(h4) accurate Second
Centered Difference approximation of the 2nd derivative at nx . Remember, to keep the same
O(h4) accuracy, while taking one more derivative than in Part a, we need to add a point to the
polynomial we used in part a.t,s01530456075y,km0356488107120
Solution
An interpolation assignment generally entails a given set of information points: in which the
values yi can,
xi x0 x1 ... xn
f(xi) y0 y1 ... yn
for instance, be the result of a few bodily measurement or they can come from a long
numerical calculation. hence we know the fee of the underlying characteristic f(x) at the set
of points xi, and we want to discover an analytic expression for f .
In interpolation, the assignment is to estimate f(x) for arbitrary x that lies among the smallest
and the most important xi
. If x is out of doors the variety of the xi’s, then the task is called extrapolation,
which is substantially greater unsafe.
with the aid of far the maximum not unusual useful paperwork utilized in interpolation are the
polynomials.
different picks encompass, as an instance, trigonometric functions and spline features
(mentioned
later during this direction).
Examples of different sorts of interpolation responsibilities include:
1. Having the set of n + 1 information factors xi
, yi, we want to understand the fee of y in the
complete c program languageperiod x = [x0, xn]; i.e. we need to find a simple formulation
which reproduces
the given points exactly.
2. If the set of statistics factors contain errors (e.g. if they are measured values), then we
ask for a components that represents the records, and if feasible, filters out the errors.
3. A feature f may be given within the shape of a pc system which is high priced
to assess. In this case, we want to find a characteristic g which offers a very good
approximation of f and is simpler to assess.
2 Polynomial interpolation
2.1 Interpolating polynomial
Given a fixed of n + 1 records points xi
, yi, we need to discover a polynomial curve that passes
via all the factors. as a consequence, we search for a non-stop curve which takes at the values yi
for every of the n+1 wonderful xi’s.
A polynomial p for which p(xi) = yi whilst zero i n is stated to interpolate the given set of
records points. The factors xi are known as nodes.
The trivial case is n = zero. right here a steady function p(x) = y0 solves the hassle.
The only case is n = 1. In this situation, the polynomial p is a directly line described via
p(x) =
xx1
x0 x1
y0 +
xx0
x1 x0
y1
= y0 +
y1 y0
x1 x0
(xx0)
here p is used for linear interpolation.
As we will see, the interpolating polynomial may be written in an expansion of paperwork,
among
these are the Newton shape and the Lag.
A radio station has a power output of 200 watts. What is the intensit.pdfpetercoiffeur18
A radio station has a power output of 200 watts. What is the intensity in watts/m2 at a distance
of 2 miles from the station? A car has an interior volume of 3.5 m^3 and is at a temperature of 30
degrees C
Solution
2)
Intensity, I = Power/area = P/A
So, for a distance of radius, r = 2 miles,
the total area of spherical space: A = 4*pi*r^2
So, A = 4*pi*(2*1.61*1000)^2 = 1.303*10^8 m2
So, I = 200/(1.303*10^8)
= 1.53*10^-6 W/m2.
21) What are the fundamental particles of lepton and quarks How man.pdfpetercoiffeur18
21) What are the fundamental particles of lepton and quarks? How many are known thus far?
Solution
Quarks are one type of matter particle. Most of the matter we see around us is made from protons
and neutrons, which are composed of quarks.
There are six quarks, but physicists usually talk about them in terms of three pairs: up/down,
charm/strange, and top/bottom.(Also, for each of these quarks, there is a corresponding
antiquark.)
Quarks have the unusual characteristic of having a fractional electric charge, unlike the proton
and electron, which have integer charges of +1 and -1 respectively. Quarks also carry another
type of charge called color charge.
The most elusive quark, the top quark, was discovered in 1995 after its existence had been
theorized for 20 years.
Quarks only exist in groups with other quarks and are never found alone. Composite particles
made of quarks are called Hadron.
Although individual quarks have fractional electrical charges, they combine such that hadrons
have a net integer electric charge. Another property of hadrons is that they have no net color
charge even though the quarks themselves carry color charge.
There are two classes of hadrons:-
Baryon: - they are any hadron which is made of three quarks. Because they are made of two up
quarks and one down quark (uud), protons are baryons. So are neutrons (udd).
Meson: - it contains one quark and one anti quark. One example of a meson is a pion which is
made of an up quark and a down anti quark. The antiparticle of a meson just has its quark and
antiquark switched, so an anti pion is made of a down quark and an up antiquark.
Because a meson consists of a particle and an antiparticle, it is very unstable. The K meson lives
much longer than most mesons, which is why it was called \"strange\" and gave this name to the
strange quark, one of its components.
Leptons
The other type of matter particles are the leptons.
There are six leptons, three of which have electrical charge and three of which do not. They
appear to be point-like particles without internal structure. The best known lepton is the electron.
The other two charged leptons are the muon and the tau which are charged like electrons but
have a lot more mass. The other leptons are the three types of neutrinos. They have no electrical
charge, very little mass, and they are very hard to find.
Quarks are one type of matter particle. Most of the matter we see around us is made from
protons and neutrons, which are composed of quarks..
Case 1-A Transition to SupervisorTristan came in on the ground fl.pdfpetercoiffeur18
Case 1-A: Transition to Supervisor
Tristan came in on the ground floor in his company and had excelled in his position for several
years when he was promoted to a supervisory position. He was excited about the increased
responsibility and money, and he also enjoyed the status and respect that came with the new title.
Tristan’s position was to supervise a new production department at a new plant site of his small
regional company. In preparation he was ordered to attend a two-week supervisor’s training
program at headquarters. As he expected, the training was focused on human resources (HR)
concerns, customer satisfaction issues, and corporate quality production expectations. Because
the new location was intended to showcase the company’s strength in quality manufacturing, he
was allowed to recruit his own team from among the company’s statewide employee pool.
Several seasoned workers, acquainted with him as a result of his time with the company,
expressed interest in the startup department.
Lauren was hired as the departmental administrative assistant and William was hired as the new
line foreman. Tristan was elated and felt that things were moving ahead quickly enough for his
superiors to be pleased with the progress he was making. He continued to fill the necessary
positions. Within a month the department was ready to get going. Everyone was excited,
attitudes were positive, and he was looking forward to the inaugural production run.
Tristan had never held a supervisory position before, yet he knew Lauren and William were both
strong employees with great work ethic. He was certain everyone he selected possessed a similar
work ethic and was driven to succeed. However, this quickly proved erroneous, and when it
became obvious the hoped-for production quality was nonexistent, everything became a dismal
failure all at once. The department failed to produce at the expected quality level, and turmoil
among the employees was widespread. During the nearly two years he was supervisor, Tristan
was never able to earn the respect of his employees or experience the success in production
quality envisioned by the company.
In reality, many first-time supervisors earn their position by simply doing well at their job;
however, without proper training, in both supervision and leadership, disappointing outcomes
like Tristan’s are more common than you would imagine. Just because an employee is good, or
even great, it does not mean he or she will be a great supervisor.
RESPONDING TO THE CASE
1-10. If you envision transitioning into a supervisory position, what can you do to ensure you
don’t end up like Tristan?
1-11. What supervisory competencies should you work to develop? Why?
1-12. Which of the four management functions do you believe most supervisors need help with?
Why do you think this is the case?
1-13. The role of supervisor can be considered a first step toward management. What are the
benefits and potential disadvantages of pursuing a management caree.
x , y Midterm Exsm-201840x Exam C httpsbb-montgomerycollege.blac.pdfpetercoiffeur18
x , y Midterm Exsm-201840x Exam C https://bb-
montgomerycollege.blackboard.com/webapps/assessment/take/isunch jsp?course assessment id-
310249 1couse542 Take Test: Mitearm Esam x Can be based on senious norms such as taboos
and less serious noms such as folkways and mores QUESTION 9 Poverty exists bee ause
someone has to be on bottom. That\'s just the way Ife is Ths statemenk telects boket O doxic O c
apitalist QUESTION 10 The way class status is reprodut.ed from generation to generation is
referted to as O Socio-politic al reproduction Social class reproduction Culture of poverty Class
regeneration QUESTION 11 The spread of fast-tood chain puts localhy owned, independent
restauravits out of business disconnects people from oaning their owe mianis of production
Which of the following statements does not reflec1 a conflict perspective on globaizabon? O The
spread of corporations ?Unique, indigenous cultures become devalued and nsk extinction abity
and inegration s people share sm/ar The spread of large corporations promotes st all arisuwers it
to seve and submit. Cick Saue All Answers to save aft
Solution
9ans ) doxic option b
Reason: it is an common belief or an opinion that some one had to be bottom that\'s why there
life exists like that
10 ans) Social class reproduction option b
Reason: from generation to generation social class reproduction is based on how the class way is
represented
11ans )The spread of large corporations promotes stability and integration as people share
similar working conditions
Option d.
Why would a cell want to express genes in an operon Why notSol.pdfpetercoiffeur18
Why would a cell want to express genes in an operon? Why not?
Solution
An operon is a cluster of genes operating together. Genes in operon are transcribed on
requirement of the cell or the genes are turned off when they are not required. Thus, cells express
genes in operons for regulation of gene transcription and to express the genes only when they are
required. An operon contains an operator gene, repressor gene and structural genes. Operator
gene to which the RNA polymerase will be bind to transcribe the genes. Operon also contains a
repressor. Repressor molecule when binds the operator, RNA polymerase cannot be bind to
operator and the transcription of genes is turned off. Thus, expression of genes in cells is
regulated by operons. Operons are observed mostly in prokaryotic cells as the genes in
prokaryotes are transcribed and translated together..
When discussing the epidemiology of virus infections, the CDC often .pdfpetercoiffeur18
When discussing the epidemiology of virus infections, the CDC often refers to the virus\' ability
to \"jump between species.\" Is infecting multiple species common for a virus? Why?
Solution
Viruses infects animal, plants, humans and bacteria.Viruses have a specific proteins on their
capsule which recognises a particular complementary receptors on host surface and interact with
them.So viruses selectively infects certain species.HIV infects only immune cells and destroys
our immune system..
What relationship is there between gobalization and development.pdfpetercoiffeur18
What relationship is there between gobalization and development?
What relationship is there between gobalization and development?
Solution
Answer)
Globalisation is a complex phenomenon that revolves around political, social and economic
spheres of the world. The vast process of globalisation involves exchange of money , trade and
technology with transfer of people. So, there are capital as well as financial flows from one
country to another.
The major relationship between globalisation and development comes from the growth in
international trade and building services like banking, insurance, shipping, finance , healthcare
and so on. The development of service sector will provide in for the all round development of the
nation. This we see as the direct relationship between globalisation and development.
Development means economic growth plus enhancing human capital which includes parameters
health , nutrition, education and clean environment. Therefore, we have the process of
interlinking between developed and developing countries due to globalisation and as a result
increased development. It has achieved the goals of economic efficiency and growth with high
profits.
But, there are some negative impact too. The indirect effect of globalisation on development is
that due to integration of economy, people and culture , it has led to fragmentation of societies. It
has ignored the goals of equity, poverty eradication and human security. The stark levels of
inequality and growing poverty level in the developing nations is the major sign showing
negative development due to globalisation. There has been no trickle-down effects of
globalisation seen as far. On the other hand , it has only made the developed nations more
wealthier while the developing nations surviving at the mercy of the developed nations..
what is the number between 4.5 and 4.75 on the number linew.pdfpetercoiffeur18
what is the number between 4.5 and 4.75 on the number line?
what is the number between 4.5 and 4.75 on the number line?
what is the number between 4.5 and 4.75 on the number line?
Solution
There are infinite number of numbers between two numbers on a number line
One of the numbers is 4.6
4.6>4.5 and 4.6<4.75.
A Strategic Approach: GenAI in EducationPeter Windle
Artificial Intelligence (AI) technologies such as Generative AI, Image Generators and Large Language Models have had a dramatic impact on teaching, learning and assessment over the past 18 months. The most immediate threat AI posed was to Academic Integrity with Higher Education Institutes (HEIs) focusing their efforts on combating the use of GenAI in assessment. Guidelines were developed for staff and students, policies put in place too. Innovative educators have forged paths in the use of Generative AI for teaching, learning and assessments leading to pockets of transformation springing up across HEIs, often with little or no top-down guidance, support or direction.
This Gasta posits a strategic approach to integrating AI into HEIs to prepare staff, students and the curriculum for an evolving world and workplace. We will highlight the advantages of working with these technologies beyond the realm of teaching, learning and assessment by considering prompt engineering skills, industry impact, curriculum changes, and the need for staff upskilling. In contrast, not engaging strategically with Generative AI poses risks, including falling behind peers, missed opportunities and failing to ensure our graduates remain employable. The rapid evolution of AI technologies necessitates a proactive and strategic approach if we are to remain relevant.
2024.06.01 Introducing a competency framework for languag learning materials ...Sandy Millin
http://sandymillin.wordpress.com/iateflwebinar2024
Published classroom materials form the basis of syllabuses, drive teacher professional development, and have a potentially huge influence on learners, teachers and education systems. All teachers also create their own materials, whether a few sentences on a blackboard, a highly-structured fully-realised online course, or anything in between. Despite this, the knowledge and skills needed to create effective language learning materials are rarely part of teacher training, and are mostly learnt by trial and error.
Knowledge and skills frameworks, generally called competency frameworks, for ELT teachers, trainers and managers have existed for a few years now. However, until I created one for my MA dissertation, there wasn’t one drawing together what we need to know and do to be able to effectively produce language learning materials.
This webinar will introduce you to my framework, highlighting the key competencies I identified from my research. It will also show how anybody involved in language teaching (any language, not just English!), teacher training, managing schools or developing language learning materials can benefit from using the framework.
Acetabularia Information For Class 9 .docxvaibhavrinwa19
Acetabularia acetabulum is a single-celled green alga that in its vegetative state is morphologically differentiated into a basal rhizoid and an axially elongated stalk, which bears whorls of branching hairs. The single diploid nucleus resides in the rhizoid.
The Roman Empire A Historical Colossus.pdfkaushalkr1407
The Roman Empire, a vast and enduring power, stands as one of history's most remarkable civilizations, leaving an indelible imprint on the world. It emerged from the Roman Republic, transitioning into an imperial powerhouse under the leadership of Augustus Caesar in 27 BCE. This transformation marked the beginning of an era defined by unprecedented territorial expansion, architectural marvels, and profound cultural influence.
The empire's roots lie in the city of Rome, founded, according to legend, by Romulus in 753 BCE. Over centuries, Rome evolved from a small settlement to a formidable republic, characterized by a complex political system with elected officials and checks on power. However, internal strife, class conflicts, and military ambitions paved the way for the end of the Republic. Julius Caesar’s dictatorship and subsequent assassination in 44 BCE created a power vacuum, leading to a civil war. Octavian, later Augustus, emerged victorious, heralding the Roman Empire’s birth.
Under Augustus, the empire experienced the Pax Romana, a 200-year period of relative peace and stability. Augustus reformed the military, established efficient administrative systems, and initiated grand construction projects. The empire's borders expanded, encompassing territories from Britain to Egypt and from Spain to the Euphrates. Roman legions, renowned for their discipline and engineering prowess, secured and maintained these vast territories, building roads, fortifications, and cities that facilitated control and integration.
The Roman Empire’s society was hierarchical, with a rigid class system. At the top were the patricians, wealthy elites who held significant political power. Below them were the plebeians, free citizens with limited political influence, and the vast numbers of slaves who formed the backbone of the economy. The family unit was central, governed by the paterfamilias, the male head who held absolute authority.
Culturally, the Romans were eclectic, absorbing and adapting elements from the civilizations they encountered, particularly the Greeks. Roman art, literature, and philosophy reflected this synthesis, creating a rich cultural tapestry. Latin, the Roman language, became the lingua franca of the Western world, influencing numerous modern languages.
Roman architecture and engineering achievements were monumental. They perfected the arch, vault, and dome, constructing enduring structures like the Colosseum, Pantheon, and aqueducts. These engineering marvels not only showcased Roman ingenuity but also served practical purposes, from public entertainment to water supply.
Introduction to AI for Nonprofits with Tapp NetworkTechSoup
Dive into the world of AI! Experts Jon Hill and Tareq Monaur will guide you through AI's role in enhancing nonprofit websites and basic marketing strategies, making it easy to understand and apply.
How to Make a Field invisible in Odoo 17Celine George
It is possible to hide or invisible some fields in odoo. Commonly using “invisible” attribute in the field definition to invisible the fields. This slide will show how to make a field invisible in odoo 17.
Embracing GenAI - A Strategic ImperativePeter Windle
Artificial Intelligence (AI) technologies such as Generative AI, Image Generators and Large Language Models have had a dramatic impact on teaching, learning and assessment over the past 18 months. The most immediate threat AI posed was to Academic Integrity with Higher Education Institutes (HEIs) focusing their efforts on combating the use of GenAI in assessment. Guidelines were developed for staff and students, policies put in place too. Innovative educators have forged paths in the use of Generative AI for teaching, learning and assessments leading to pockets of transformation springing up across HEIs, often with little or no top-down guidance, support or direction.
This Gasta posits a strategic approach to integrating AI into HEIs to prepare staff, students and the curriculum for an evolving world and workplace. We will highlight the advantages of working with these technologies beyond the realm of teaching, learning and assessment by considering prompt engineering skills, industry impact, curriculum changes, and the need for staff upskilling. In contrast, not engaging strategically with Generative AI poses risks, including falling behind peers, missed opportunities and failing to ensure our graduates remain employable. The rapid evolution of AI technologies necessitates a proactive and strategic approach if we are to remain relevant.
Unit 8 - Information and Communication Technology (Paper I).pdfThiyagu K
This slides describes the basic concepts of ICT, basics of Email, Emerging Technology and Digital Initiatives in Education. This presentations aligns with the UGC Paper I syllabus.
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.
1)(JAVA) Extend the Binary Search Tree ADT to include a public metho.pdf
1. 1)(JAVA) Extend the Binary Search Tree ADT to include a public method leafCount that returns
the number of leaf nodes in the tree.
Thank You in Advanced.
Below, I also have attached the BinarySearchTree and the Interface File.
BinarySearchTree:
//----------------------------------------------------------------------------
// BinarySearchTree.java by Dale/Joyce/Weems Chapter 8
//
// Defines all constructs for a reference-based BST
//----------------------------------------------------------------------------
package ch08.trees;
import ch05.queues.*;
import ch03.stacks.*;
import support.BSTNode;
public class BinarySearchTree>
implements BSTInterface
{
protected BSTNode root; // reference to the root of this BST
boolean found; // used by remove
// for traversals
protected LinkedUnbndQueue inOrderQueue; // queue of info
protected LinkedUnbndQueue preOrderQueue; // queue of info
protected LinkedUnbndQueue postOrderQueue; // queue of info
public BinarySearchTree()
// Creates an empty BST object.
{
root = null;
}
public boolean isEmpty()
// Returns true if this BST is empty; otherwise, returns false.
{
return (root == null);
}
2. private int recSize(BSTNode tree)
// Returns the number of elements in tree.
{
if (tree == null)
return 0;
else
return recSize(tree.getLeft()) + recSize(tree.getRight()) + 1;
}
public int size()
// Returns the number of elements in this BST.
{
return recSize(root);
}
public int size2()
// Returns the number of elements in this BST.
{
int count = 0;
if (root != null)
{
LinkedStack> hold = new LinkedStack>();
BSTNode currNode;
hold.push(root);
while (!hold.isEmpty())
{
currNode = hold.top();
hold.pop();
count++;
if (currNode.getLeft() != null)
hold.push(currNode.getLeft());
if (currNode.getRight() != null)
hold.push(currNode.getRight());
}
}
return count;
}
private boolean recContains(T element, BSTNode tree)
3. // Returns true if tree contains an element e such that
// e.compareTo(element) == 0; otherwise, returns false.
{
if (tree == null)
return false; // element is not found
else if (element.compareTo(tree.getInfo()) < 0)
return recContains(element, tree.getLeft()); // Search left subtree
else if (element.compareTo(tree.getInfo()) > 0)
return recContains(element, tree.getRight()); // Search right subtree
else
return true; // element is found
}
public boolean contains (T element)
// Returns true if this BST contains an element e such that
// e.compareTo(element) == 0; otherwise, returns false.
{
return recContains(element, root);
}
private T recGet(T element, BSTNode tree)
// Returns an element e from tree such that e.compareTo(element) == 0;
// if no such element exists, returns null.
{
if (tree == null)
return null; // element is not found
else if (element.compareTo(tree.getInfo()) < 0)
return recGet(element, tree.getLeft()); // get from left subtree
else
if (element.compareTo(tree.getInfo()) > 0)
return recGet(element, tree.getRight()); // get from right subtree
else
return tree.getInfo(); // element is found
}
public T get(T element)
// Returns an element e from this BST such that e.compareTo(element) == 0;
// if no such element exists, returns null.
4. {
return recGet(element, root);
}
private BSTNode recAdd(T element, BSTNode tree)
// Adds element to tree; tree retains its BST property.
{
if (tree == null)
// Addition place found
tree = new BSTNode(element);
else if (element.compareTo(tree.getInfo()) <= 0)
tree.setLeft(recAdd(element, tree.getLeft())); // Add in left subtree
else
tree.setRight(recAdd(element, tree.getRight())); // Add in right subtree
return tree;
}
public void add (T element)
// Adds element to this BST. The tree retains its BST property.
{
root = recAdd(element, root);
}
private T getPredecessor(BSTNode tree)
// Returns the information held in the rightmost node in tree
{
while (tree.getRight() != null)
tree = tree.getRight();
return tree.getInfo();
}
private BSTNode removeNode(BSTNode tree)
// Removes the information at the node referenced by tree.
// The user's data in the node referenced by tree is no
// longer in the tree. If tree is a leaf node or has only
// a non-null child pointer, the node pointed to by tree is
// removed; otherwise, the user's data is replaced by its
// logical predecessor and the predecessor's node is removed.
{
T data;
5. if (tree.getLeft() == null)
return tree.getRight();
else if (tree.getRight() == null)
return tree.getLeft();
else
{
data = getPredecessor(tree.getLeft());
tree.setInfo(data);
tree.setLeft(recRemove(data, tree.getLeft()));
return tree;
}
}
private BSTNode recRemove(T element, BSTNode tree)
// Removes an element e from tree such that e.compareTo(element) == 0
// and returns true; if no such element exists, returns false.
{
if (tree == null)
found = false;
else if (element.compareTo(tree.getInfo()) < 0)
tree.setLeft(recRemove(element, tree.getLeft()));
else if (element.compareTo(tree.getInfo()) > 0)
tree.setRight(recRemove(element, tree.getRight()));
else
{
tree = removeNode(tree);
found = true;
}
return tree;
}
public boolean remove (T element)
// Removes an element e from this BST such that e.compareTo(element) == 0
// and returns true; if no such element exists, returns false.
{
root = recRemove(element, root);
return found;
}
6. private void inOrder(BSTNode tree)
// Initializes inOrderQueue with tree elements in inOrder order.
{
if (tree != null)
{
inOrder(tree.getLeft());
inOrderQueue.enqueue(tree.getInfo());
inOrder(tree.getRight());
}
}
private void preOrder(BSTNode tree)
// Initializes preOrderQueue with tree elements in preOrder order.
{
if (tree != null)
{
preOrderQueue.enqueue(tree.getInfo());
preOrder(tree.getLeft());
preOrder(tree.getRight());
}
}
private void postOrder(BSTNode tree)
// Initializes postOrderQueue with tree elements in postOrder order.
{
if (tree != null)
{
postOrder(tree.getLeft());
postOrder(tree.getRight());
postOrderQueue.enqueue(tree.getInfo());
}
}
public int reset(int orderType)
// Initializes current position for an iteration through this BST
// in orderType order. Returns current number of nodes in the BST.
{
int numNodes = size();
if (orderType == INORDER)
7. {
inOrderQueue = new LinkedUnbndQueue();
inOrder(root);
}
else
if (orderType == PREORDER)
{
preOrderQueue = new LinkedUnbndQueue();
preOrder(root);
}
if (orderType == POSTORDER)
{
postOrderQueue = new LinkedUnbndQueue();
postOrder(root);
}
return numNodes;
}
public T getNext (int orderType)
// Preconditions: The BST is not empty
// The BST has been reset for orderType
// The BST has not been modified since the most recent reset
// The end of orderType iteration has not been reached
//
// Returns the element at the current position on this BST for orderType
// and advances the value of the current position based on the orderType.
{
if (orderType == INORDER)
return inOrderQueue.dequeue();
else
if (orderType == PREORDER)
return preOrderQueue.dequeue();
else
if (orderType == POSTORDER)
return postOrderQueue.dequeue();
else return null;
}
8. }
BSTInterface:
//----------------------------------------------------------------------------
// BSTInterface.java by Dale/Joyce/Weems Chapter 8
//
// Interface for a class that implements a binary search tree (BST).
//
// The trees are unbounded and allow duplicate elements, but do not allow null
// elements. As a general precondition, null elements are not passed as
// arguments to any of the methods.
//
// The tree supports iteration through its elements in INORDER, PREORDER,
// and POSTORDER.
//----------------------------------------------------------------------------
package ch08.trees;
public interface BSTInterface>
{
// used to specify traversal order
static final int INORDER = 1;
static final int PREORDER = 2;
static final int POSTORDER = 3;
boolean isEmpty();
// Returns true if this BST is empty; otherwise, returns false.
int size();
// Returns the number of elements in this BST.
boolean contains (T element);
// Returns true if this BST contains an element e such that
// e.compareTo(element) == 0; otherwise, returns false.
boolean remove (T element);
// Removes an element e from this BST such that e.compareTo(element) == 0
// and returns true; if no such element exists, returns false.
T get(T element);
// Returns an element e from this BST such that e.compareTo(element) == 0;
9. // if no such element exists, returns null.
void add (T element);
// Adds element to this BST. The tree retains its BST property.
int reset(int orderType);
// Initializes current position for an iteration through this BST
// in orderType order. Returns current number of nodes in the BST.
T getNext (int orderType);
// Preconditions: The BST is not empty
// The BST has been reset for orderType
// The BST has not been modified since the most recent reset
// The end of orderType iteration has not been reached
//
// Returns the element at the current position on this BST for orderType
// and advances the value of the current position based on the orderType.
}
Solution
import ch05.queues.*;
import ch03.stacks.*;
import support.BSTNode;
public category BinarySearchTree>
implements BSTInterface
relevance the basis of this BST
boolean found; // utilized by take away
// for traversals
protected LinkedUnbndQueue inOrderQueue; // queue of information
protected LinkedUnbndQueue preOrderQueue; // queue of information
protected LinkedUnbndQueue postOrderQueue; // queue of information
public BinarySearchTree()
// Creates Associate in Nursing empty BST object.
public mathematician isEmpty()
// Returns true if this BST is empty; otherwise, returns false.
private int recSize(BSTNode tree)
10. // Returns the quantity of components in tree.
public int size()
// Returns the quantity of components during this BST.
public int size2()
// Returns the quantity of components during this BST.
}
return count;
}
private mathematician recContains(T part, BSTNode tree)
// Returns true if tree contains a part e such
// e.compareTo(element) == zero; otherwise, returns false.
{
if (tree == null)
return false; // part isn't found
else if (element.compareTo(tree.getInfo()) < 0)
return recContains(element, tree.getLeft()); // Search left subtree
else if (element.compareTo(tree.getInfo()) > 0)
return recContains(element, tree.getRight()); // Search right subtree
else
return true; // part is found
}
public mathematician contains (T element)
// Returns true if this BST contains a part e such
// e.compareTo(element) == zero; otherwise, returns false.
private T recGet(T part, BSTNode tree)
// Returns a part e from tree such e.compareTo(element) == zero;
// if no such part exists, returns null.
{
if (tree == null)
return null; // part isn't found
else if (element.compareTo(tree.getInfo()) < 0)
return recGet(element, tree.getLeft()); // get from left subtree
else
if (element.compareTo(tree.getInfo()) > 0)
return recGet(element, tree.getRight()); // get from right subtree
11. else
return tree.getInfo(); // part is found
}
public T get(T element)
// Returns a part e from this BST such e.compareTo(element) == 0;
// if no such part exists, returns null.
private BSTNode recAdd(T part, BSTNode tree)
// Adds part to tree; tree retains its BST property.
public void add (T element)
// Adds part to the current BST. The tree retains its BST property.
private T getPredecessor(BSTNode tree)
// Returns the knowledge command within the right node in tree
private BSTNode removeNode(BSTNode tree)
// Removes the knowledge at the node documented by tree.
// The user's information within the node documented by tree is not any
// longer within the tree. If tree could be a leaf node or has solely
// a non-null kid pointer, the node pointed to by tree is
// removed; otherwise, the user's information is replaced by its
// logical forerunner and therefore the predecessor's node is removed.
}
private BSTNode recRemove(T part, BSTNode tree)
// Removes a part e from tree such e.compareTo(element) == 0
// and returns true; if no such part exists, returns false.
return tree;
}
public mathematician take away (T element)
// Removes a part e from this BST such e.compareTo(element) == 0
// and returns true; if no such part exists, returns false.
private void inOrder(BSTNode tree)
// Initializes inOrderQueue with tree components in inOrder order.
}
private void preOrder(BSTNode tree)
// Initializes preOrderQueue with tree components in preOrder order.
}
private void postOrder(BSTNode tree)
// Initializes postOrderQueue with tree components in postOrder order.
12. }
public int reset(int orderType)
// Initializes current position for Associate in Nursing iteration through this BST
// in orderType order. Returns current variety of nodes within the BST.
else
if (orderType == PREORDER)
if (orderType == POSTORDER)
return numNodes;
}
public T getNext (int orderType)
// Preconditions: The BST isn't empty
// The BST has been reset for orderType
// The BST has not been changed since the foremost recent reset
// the tip of orderType iteration has not been reached
//
// Returns the part at the present position on this BST for orderType
// and advances the worth of the present position supported the orderType.
come back null;
}
}
BSTInterface:
//----------------------------------------------------------------------------
// BSTInterface.java by Dale/Joyce/Weems Chapter eight
//
// Interface for a category that implements a binary search tree (BST).
//
// The trees square measure boundless and permit duplicate components, however don't enable
null
// components. As a general precondition, null components don't seem to be passed as
// arguments to any of the strategies.
//
// The tree supports iteration through its components in INORDER, PREORDER,
// and POSTORDER.
//----------------------------------------------------------------------------
package ch08.trees;
public interface BSTInterface>
13. accustomed specify traversal order
static final int INORDER = 1;
static final int PREORDER = 2;
static final int POSTORDER = 3;
boolean isEmpty();
// Returns true if this BST is empty; otherwise, returns false.
int size();
// Returns the quantity of components during this BST.
boolean contains (T element);
// Returns true if this BST contains a part e such
// e.compareTo(element) == 0; otherwise, returns false.
boolean take away (T element);
// Removes a part e from this BST such e.compareTo(element) == 0
// and returns true; if no such part exists, returns false.
T get(T element);
// Returns a part e from this BST such e.compareTo(element) == 0;
// if no such part exists, returns null.
void add (T element);
// Adds part to the current BST. The tree retains its BST property.
int reset(int orderType);
// Initializes current position for Associate in Nursing iteration through this BST
// in orderType order. Returns current variety of nodes within the BST.
T getNext (int orderType);
// Preconditions: The BST isn't empty
// The BST has been reset for orderType
// The BST has not been changed since the foremost recent reset
// the tip of orderType iteration has not been reached
//
// Returns the part at the present position on this BST for orderType
// and advances the worth of the present position supported the orderType.
}