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(.
(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.
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 == .
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.
03/.DS_Store
__MACOSX/03/._.DS_Store
03/A2/.DS_Store
__MACOSX/03/A2/._.DS_Store
03/A2/build.xml
Some useful functions for working with pipes.
__MACOSX/03/A2/._build.xml
03/A2/src/.DS_Store
__MACOSX/03/A2/src/._.DS_Store
03/A2/src/nz/.DS_Store
__MACOSX/03/A2/src/nz/._.DS_Store
03/A2/src/nz/retro_freedom/.DS_Store
__MACOSX/03/A2/src/nz/retro_freedom/._.DS_Store
03/A2/src/nz/retro_freedom/dsa2016/.DS_Store
__MACOSX/03/A2/src/nz/retro_freedom/dsa2016/._.DS_Store
03/A2/src/nz/retro_freedom/dsa2016/pair/Pair.java03/A2/src/nz/retro_freedom/dsa2016/pair/Pair.javapackage nz.retro_freedom.dsa2016.pair;
import java.util.*;
/**
* @author
* @version 1.0
*
* A data type representing generic, non-{@code null} pairs.
* Pairs cannot be modified once created - if you need to change a pair,
* make a new one instead.
*/
publicclassPair<T1, T2>{
/**
* Makes a new pair.
*
* @param left the left side of the pair (cannot be {@code null}).
* @param right the right side of the pair (cannot be {@code null}).
* @return a new pair with the given left and right sides.
* @throws NullPointerException if left or right are {@code null}.
*/
publicstatic<T1, T2>Pair<T1, T2> make (T1 left, T2 right){
Objects.requireNonNull(left,"left cannot be null.");
Objects.requireNonNull(right,"right cannot be null.");
returnnewPair<T1, T2>(left, right);
}
/**
* Convenience factory for replacing left side of an existing pair.
*
* @param p a pair (cannot be {@code null}).
* @param left a new left element (cannot be {@code null}).
* @return a new pair which is the same as p, but with a new left element.
* @throws NullPointerException if an argument is {@code null}.
*/
publicstatic<T1, T2>Pair<T1, T2> newLeft (Pair<T1, T2> p, T1 left){
Objects.requireNonNull (p,"p cannot be null.");
return make (left, p.right ());
}
/**
* Convenience factory for replacing right side of an existing pair.
*
* @param p a pair (cannot be {@code null}).
* @param right a new right element (cannot be {@code null}).
* @return a new pair which is the same as p, but with a new right element.
* @throws NullPointerException if an argument is {@code null}.
*/
publicstatic<T1, T2>Pair<T1, T2> newRight (Pair<T1, T2> p, T2 right){
Objects.requireNonNull (p,"p cannot be null.");
return make (p.left (), right);
}
/**
* Compares on both elements.
*
* @param o a thing to compare to.
* @return true if both sides of both pairs match.
*/
@Override
publicboolean equals (Object o){
if(o instanceofPair<?,?>){
Pair<?,?> p =(Pair<?,?>)o;
if(left.equals (p.left)&&
right.equals (p.right)){
returntrue;
}
}
returnfalse;
}
/**
* Hashes on both sides.
*
* @return a unique code representing a pair.
*/
@Override
publicint hashCode (){
int result =1;
resu ...
This is a c++ binary search program I worked so far but still cant g.pdfkostikjaylonshaewe47
This is a c++ binary search program I worked so far but still cant get it right.
Can anyone help me? Big thanks!!
the client should not be modified
/*
*File: client.cpp
*Author: Yingwu Zhu
*Warning: do not change this file and use it as is.
*Last Modififcation: 10/21/2016
*/
#include
#include
#include
#include
#include
#include \"bst.h\"
using namespace std;
int main(int argc, char* argv[]) {
if (argc != 2) {
cout << \"Format: \" << argv[0] << \" [data file]\" << endl;
return 0;
}
ifstream fin(argv[1]);
int cases;
fin >> cases;
int passed = 0;
for (int i = 1; i <= cases; i++) {
cout << \"Checking test case #\" << i << \" ... \";
BST T;
set S;
int n, x;
fin >> n;
bool ok = true;
vector tmp;
int rem = 0;
for (int j = 0; j < n; j++) {
fin >> x;
T.Insert(x);
S.insert(x);
ok &= (T.Search(x) && T.RecurSearch(x));
if (tmp.empty())
tmp.push_back(x);
if (rand()%10 < 3) {
T.Erase(tmp[0]);
S.erase(tmp[0]);
ok &= (T.Search(tmp[0]) == false);
tmp.pop_back();
rem++;
}
}
if (rem
ok &= (T.MaxElement() == *S.rbegin());
while (!S.empty() && !T.Empty()) {
int x = T.MinElement();
ok &= (x == *S.begin());
T.Erase(x);
S.erase(S.begin());
}
cout << (ok ? \"Passed!\" : \"Failed\") << endl;
passed += ok;
}
cout << passed << \" of \" << cases << \" test cases have passed!\ \";
if (passed == cases)
cout << endl << \"Congratulations! Good to Submit Your Code\ \";
else if ((double)passed/cases >= 0.95)
cout << endl << \"You are almost there, but need to fix some bugs.\ \";
else
cout << endl << \"Your code needs a lot of fixes for submission\ \";
return 0;
}
=====================================================================
=======
//bst.h
#ifndef _BST_H_
#define _BST_H_
#include
using namespace std;
class BST {
private:
class Node {
public:
int data;
Node* left;
Node* right;
};
Node* root; //root node pointer
//you may add your auxiliary functions here!
public:
BST(); //constructor
~BST(); //destructor
bool Empty() const;
void Insert(int val);
int MinElement() const;
int MaxElement() const;
bool Search(int val) const;
bool RecurSearch(int val) const;
void Erase(int val);
};
#endif
=====================================================================
=======
/*
bst.cpp
Subject: Binary Seach Tree
Modification Time:10/26/2016
*/
#include
#include\"bst.h\"
using namespace std;
BST::BST(){
root= NULL;
}
BST::~BST(){
delete root;
delete root->left;
delete root->right;
}
bool BST::Empty() const {
return data;
}
void BST::Insert(int val){
Node* p= new Node;
p->data= val;
Node* cur = root;
if(val < cur->data){
cur = cur -> left;
}
else{
right->next=val;
}
}
int BST::MinElement() const {
Node* cur;
while(cur->left != NULL){
cur = cur->left;
}
return(cur->data);
}
int BST::MaxElement() const{
if(root==NULL){
return 0;
}
if(root->left>root->data){
root->data=root->right;
}
else if(root->right>root->data){
root->data=root->right;
}
return root->data;
}
bool BST:: Search(int val) const{
Node* cur;
cur = root;
while(cur!=NULL){
if(cur->data == val){
return true;
}
else if(cur->data .
in this assignment you are asked to write a simple driver program an.pdfmichardsonkhaicarr37
in this assignment you are asked to write a simple driver program and set of functions (maybein
a library) that can be performed on a binary search tree.
Your program should allow user to insert/delete integer values into the binary search tree along
with several other operations on the binary search tree. You can use the code given in slides. But
this time your key will be int! Specifically, your program will ask user to enter a command and
related parameters (if any) in a loop, and then perform the given commands. Here is the list of
commands that your program must implement:
* insert
*find\'
*delete
*list inorder
*list preorder
*list postorder
*list levelorder
* max
* min
* height
*count
* sum
*quit
As always, make sure you release (free) the dynamically allocated memories if you allocate any
memory in your programs. So, before submitting your program, run it with valgrind to see if
there is any memory leakage
//my proggram in C
struct tree_node {
int data;
struct tree_node *left, *right;
}
typedef struct nodeT {
int key;
struct nodeT *left, *right;
} nodeT, *treeT;
int main(){
while (TRUE) {
printf(\"> \");
line = GetLine();
ch = toupper(line[0]);
switch (ch) {
case \'I\': insert(); break;
case \'F\': find(); break;
case \'D\': delete(); break;
case \'LI\': listInorder; break;
case \'LPR\': listPreorder(); break;
case \'LPO\': listPostorder(); break;
case \'MAX\': max(); break;
case \'min\': min(); break;
case \'H\': height(); break;
case \'C\': count(); break;
case \'S\': sum(); break;
case \'Q\': exit(0);
default:printf(\"Illegal command\ \"); break;
}
}
}
nodeT *FindNode(nodeT *t, int key){
while(t !=NULL) {
if (key == t->key) return t;
if (key < t->key) {
t = t->left;
} else {
t = t->right;
}
return NULL;
}
void delete(nodeT **p){
nodeT
*target;
target=*p;
if (target->left==NULL && target->right==NULL) {
*p=NULL;
} else if (target->left == NULL) {
*p=target->right;
} else
if (target->right == NULL) {
*p=target->left;
} else {
/* target has two children, see next slide */
}
free(target);
}
void listInorder(nodeT *T){
if (t != NULL) {
DisplayTree(t->left);
printf(“%d “, t->key);
DisplayTree(t->right);
}
}
void listPreorder(nodeT *t) {
if (t != NULL) {
printf(“%d “, t->key);
DisplayTree(t->left);
DisplayTree(t->right);
}
}
void listPostOrder(nodeT *t){
if (t != NULL) {
DisplayTree(t->left);
DisplayTree(t->right);
printf(“%d “, t->key);
}
}
void intsert(nodeT **tptr, int key){
nodeT*t, *tmp;
t=*tptr;
if (t == NULL) {
tmp=New(nodeT*);
tmp->key = key;
tmp->left=tmp->right=NULL;
*tptr=tmp;
return;
}
if (key < t->key) {
InsertNode
(&t->left, key);
} else {
InsertNode(&t->right, key);
}
}
int height(nodeT *t){
if (t == NULL)
return 0;
else
return (1 + maximumof(
height(t->left),
height(t->right)) );
}
int sum(struct tree_node *p){
if (p == NULL)
return 0;
else
return (p->data +
sum(p->left) +
sum(p->right) );
}
Solution
1. /*
2. * Java Program to Implement Binary Search Tree
3. */
4.
5. import java.util.Scanner;
6.
7. /* Class BSTNode */
8. cl.
Consider a double-linked linked list implementation with the followin.pdfsales98
Consider a double-linked linked list implementation with the following node: struct Node {int
data; Node *prev; Node *next;} Write a copyList method that is not a member of any class.
The method should take a head pointer and return another pointer. Do not modify the input.
Solution
struct Node {
Node *prev; // previous node
Node *next; // next node
int data; // stored value
};
#include
#include \"List.h\" // std: #include
using namespace std;
typedef DataList ; // std: typedef list Data;
int main() {
Data k;
// back stuff
k.push_back(5);
k.push_back(6);
cout << k.back() << endl;
k.pop_back();
// front stuff
k.push_front(4);
k.push_front(3);
cout << k.front() << endl;
k.pop_front();
// forward iterator
Data::iterator pos;
for (pos = k.begin(); pos != k.end(); ++pos)
cout << *pos << endl;
// output and delete list
while (!k.empty()) {
cout << k.front() << endl;
k.pop_front();
}
k.push_front(5);
k.push_front(6);
// remove and erase
k.remove(5);
pos = k.begin();
k.erase(pos);
k.push_front(5);
k.push_front(6);
// copy constructor
Data l = k;
// assignment operator
Data m;
m = k;
return 0;
}
// List.h
struct Node;
classIterator List;
class List {
public:
typedef ListIterator iterator;
// constructor
List();
// destructor
virtual ~List();
// copy constructor
List(const List& k);
// assignment operator
List& operator=(const List& k);
// insert value in front of list
void push_front(double data);
// insert value in back of list
void push_back(double data);
// delete value from front of list
void pop_front();
// delete value from back of list
void pop_back();
// return value on front of list
double front() const;
// return value on back of list
double back() const;
// delete value specified by iterator
void erase(const iterator& i);
// delete all nodes with specified value
void remove(double data);
// return true if list is empty
bool empty() const;
// return reference to first element in list
iterator begin() const;
// return reference to one past last element in list
iterator end() const;
private:
Node *head; // head of list
};
class ListIterator {
public:
// default constructor
ListIterator() {
i = 0;
}
// construct iterator for given pointer (used for begin/end)
ListIterator(Node *p) {
i = p;
}
// convert iterator to Node*
operator Node*() const {
return i;
}
// test two iterators for not equal
bool operator!=(const ListIterator& k) const {
return i != k.i;
}
// preincrement operator
ListIterator& operator++() {
i = i->next;
return *this;
}
// return value associated with iterator
double& operator*() const {
return i->data;
}
private:
Node *i; // current value of iterator
};
list.cpp
// delete list
static void deleteList(Node *head) {
Node *p = head->next;
while (p != head) {
Node *next = p->next;
delete p;
p = next;
}
delete head;
}
// copy list
static void copyList(const Node *from, Node *&to) {
// create dummy header
to = new Node;
to->next = to->prev = to;
// copy nodes
for (Node *p = from->next; p != from; p = p->next) {
Node *t = new Node;
t.
(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.
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 == .
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.
03/.DS_Store
__MACOSX/03/._.DS_Store
03/A2/.DS_Store
__MACOSX/03/A2/._.DS_Store
03/A2/build.xml
Some useful functions for working with pipes.
__MACOSX/03/A2/._build.xml
03/A2/src/.DS_Store
__MACOSX/03/A2/src/._.DS_Store
03/A2/src/nz/.DS_Store
__MACOSX/03/A2/src/nz/._.DS_Store
03/A2/src/nz/retro_freedom/.DS_Store
__MACOSX/03/A2/src/nz/retro_freedom/._.DS_Store
03/A2/src/nz/retro_freedom/dsa2016/.DS_Store
__MACOSX/03/A2/src/nz/retro_freedom/dsa2016/._.DS_Store
03/A2/src/nz/retro_freedom/dsa2016/pair/Pair.java03/A2/src/nz/retro_freedom/dsa2016/pair/Pair.javapackage nz.retro_freedom.dsa2016.pair;
import java.util.*;
/**
* @author
* @version 1.0
*
* A data type representing generic, non-{@code null} pairs.
* Pairs cannot be modified once created - if you need to change a pair,
* make a new one instead.
*/
publicclassPair<T1, T2>{
/**
* Makes a new pair.
*
* @param left the left side of the pair (cannot be {@code null}).
* @param right the right side of the pair (cannot be {@code null}).
* @return a new pair with the given left and right sides.
* @throws NullPointerException if left or right are {@code null}.
*/
publicstatic<T1, T2>Pair<T1, T2> make (T1 left, T2 right){
Objects.requireNonNull(left,"left cannot be null.");
Objects.requireNonNull(right,"right cannot be null.");
returnnewPair<T1, T2>(left, right);
}
/**
* Convenience factory for replacing left side of an existing pair.
*
* @param p a pair (cannot be {@code null}).
* @param left a new left element (cannot be {@code null}).
* @return a new pair which is the same as p, but with a new left element.
* @throws NullPointerException if an argument is {@code null}.
*/
publicstatic<T1, T2>Pair<T1, T2> newLeft (Pair<T1, T2> p, T1 left){
Objects.requireNonNull (p,"p cannot be null.");
return make (left, p.right ());
}
/**
* Convenience factory for replacing right side of an existing pair.
*
* @param p a pair (cannot be {@code null}).
* @param right a new right element (cannot be {@code null}).
* @return a new pair which is the same as p, but with a new right element.
* @throws NullPointerException if an argument is {@code null}.
*/
publicstatic<T1, T2>Pair<T1, T2> newRight (Pair<T1, T2> p, T2 right){
Objects.requireNonNull (p,"p cannot be null.");
return make (p.left (), right);
}
/**
* Compares on both elements.
*
* @param o a thing to compare to.
* @return true if both sides of both pairs match.
*/
@Override
publicboolean equals (Object o){
if(o instanceofPair<?,?>){
Pair<?,?> p =(Pair<?,?>)o;
if(left.equals (p.left)&&
right.equals (p.right)){
returntrue;
}
}
returnfalse;
}
/**
* Hashes on both sides.
*
* @return a unique code representing a pair.
*/
@Override
publicint hashCode (){
int result =1;
resu ...
This is a c++ binary search program I worked so far but still cant g.pdfkostikjaylonshaewe47
This is a c++ binary search program I worked so far but still cant get it right.
Can anyone help me? Big thanks!!
the client should not be modified
/*
*File: client.cpp
*Author: Yingwu Zhu
*Warning: do not change this file and use it as is.
*Last Modififcation: 10/21/2016
*/
#include
#include
#include
#include
#include
#include \"bst.h\"
using namespace std;
int main(int argc, char* argv[]) {
if (argc != 2) {
cout << \"Format: \" << argv[0] << \" [data file]\" << endl;
return 0;
}
ifstream fin(argv[1]);
int cases;
fin >> cases;
int passed = 0;
for (int i = 1; i <= cases; i++) {
cout << \"Checking test case #\" << i << \" ... \";
BST T;
set S;
int n, x;
fin >> n;
bool ok = true;
vector tmp;
int rem = 0;
for (int j = 0; j < n; j++) {
fin >> x;
T.Insert(x);
S.insert(x);
ok &= (T.Search(x) && T.RecurSearch(x));
if (tmp.empty())
tmp.push_back(x);
if (rand()%10 < 3) {
T.Erase(tmp[0]);
S.erase(tmp[0]);
ok &= (T.Search(tmp[0]) == false);
tmp.pop_back();
rem++;
}
}
if (rem
ok &= (T.MaxElement() == *S.rbegin());
while (!S.empty() && !T.Empty()) {
int x = T.MinElement();
ok &= (x == *S.begin());
T.Erase(x);
S.erase(S.begin());
}
cout << (ok ? \"Passed!\" : \"Failed\") << endl;
passed += ok;
}
cout << passed << \" of \" << cases << \" test cases have passed!\ \";
if (passed == cases)
cout << endl << \"Congratulations! Good to Submit Your Code\ \";
else if ((double)passed/cases >= 0.95)
cout << endl << \"You are almost there, but need to fix some bugs.\ \";
else
cout << endl << \"Your code needs a lot of fixes for submission\ \";
return 0;
}
=====================================================================
=======
//bst.h
#ifndef _BST_H_
#define _BST_H_
#include
using namespace std;
class BST {
private:
class Node {
public:
int data;
Node* left;
Node* right;
};
Node* root; //root node pointer
//you may add your auxiliary functions here!
public:
BST(); //constructor
~BST(); //destructor
bool Empty() const;
void Insert(int val);
int MinElement() const;
int MaxElement() const;
bool Search(int val) const;
bool RecurSearch(int val) const;
void Erase(int val);
};
#endif
=====================================================================
=======
/*
bst.cpp
Subject: Binary Seach Tree
Modification Time:10/26/2016
*/
#include
#include\"bst.h\"
using namespace std;
BST::BST(){
root= NULL;
}
BST::~BST(){
delete root;
delete root->left;
delete root->right;
}
bool BST::Empty() const {
return data;
}
void BST::Insert(int val){
Node* p= new Node;
p->data= val;
Node* cur = root;
if(val < cur->data){
cur = cur -> left;
}
else{
right->next=val;
}
}
int BST::MinElement() const {
Node* cur;
while(cur->left != NULL){
cur = cur->left;
}
return(cur->data);
}
int BST::MaxElement() const{
if(root==NULL){
return 0;
}
if(root->left>root->data){
root->data=root->right;
}
else if(root->right>root->data){
root->data=root->right;
}
return root->data;
}
bool BST:: Search(int val) const{
Node* cur;
cur = root;
while(cur!=NULL){
if(cur->data == val){
return true;
}
else if(cur->data .
in this assignment you are asked to write a simple driver program an.pdfmichardsonkhaicarr37
in this assignment you are asked to write a simple driver program and set of functions (maybein
a library) that can be performed on a binary search tree.
Your program should allow user to insert/delete integer values into the binary search tree along
with several other operations on the binary search tree. You can use the code given in slides. But
this time your key will be int! Specifically, your program will ask user to enter a command and
related parameters (if any) in a loop, and then perform the given commands. Here is the list of
commands that your program must implement:
* insert
*find\'
*delete
*list inorder
*list preorder
*list postorder
*list levelorder
* max
* min
* height
*count
* sum
*quit
As always, make sure you release (free) the dynamically allocated memories if you allocate any
memory in your programs. So, before submitting your program, run it with valgrind to see if
there is any memory leakage
//my proggram in C
struct tree_node {
int data;
struct tree_node *left, *right;
}
typedef struct nodeT {
int key;
struct nodeT *left, *right;
} nodeT, *treeT;
int main(){
while (TRUE) {
printf(\"> \");
line = GetLine();
ch = toupper(line[0]);
switch (ch) {
case \'I\': insert(); break;
case \'F\': find(); break;
case \'D\': delete(); break;
case \'LI\': listInorder; break;
case \'LPR\': listPreorder(); break;
case \'LPO\': listPostorder(); break;
case \'MAX\': max(); break;
case \'min\': min(); break;
case \'H\': height(); break;
case \'C\': count(); break;
case \'S\': sum(); break;
case \'Q\': exit(0);
default:printf(\"Illegal command\ \"); break;
}
}
}
nodeT *FindNode(nodeT *t, int key){
while(t !=NULL) {
if (key == t->key) return t;
if (key < t->key) {
t = t->left;
} else {
t = t->right;
}
return NULL;
}
void delete(nodeT **p){
nodeT
*target;
target=*p;
if (target->left==NULL && target->right==NULL) {
*p=NULL;
} else if (target->left == NULL) {
*p=target->right;
} else
if (target->right == NULL) {
*p=target->left;
} else {
/* target has two children, see next slide */
}
free(target);
}
void listInorder(nodeT *T){
if (t != NULL) {
DisplayTree(t->left);
printf(“%d “, t->key);
DisplayTree(t->right);
}
}
void listPreorder(nodeT *t) {
if (t != NULL) {
printf(“%d “, t->key);
DisplayTree(t->left);
DisplayTree(t->right);
}
}
void listPostOrder(nodeT *t){
if (t != NULL) {
DisplayTree(t->left);
DisplayTree(t->right);
printf(“%d “, t->key);
}
}
void intsert(nodeT **tptr, int key){
nodeT*t, *tmp;
t=*tptr;
if (t == NULL) {
tmp=New(nodeT*);
tmp->key = key;
tmp->left=tmp->right=NULL;
*tptr=tmp;
return;
}
if (key < t->key) {
InsertNode
(&t->left, key);
} else {
InsertNode(&t->right, key);
}
}
int height(nodeT *t){
if (t == NULL)
return 0;
else
return (1 + maximumof(
height(t->left),
height(t->right)) );
}
int sum(struct tree_node *p){
if (p == NULL)
return 0;
else
return (p->data +
sum(p->left) +
sum(p->right) );
}
Solution
1. /*
2. * Java Program to Implement Binary Search Tree
3. */
4.
5. import java.util.Scanner;
6.
7. /* Class BSTNode */
8. cl.
Consider a double-linked linked list implementation with the followin.pdfsales98
Consider a double-linked linked list implementation with the following node: struct Node {int
data; Node *prev; Node *next;} Write a copyList method that is not a member of any class.
The method should take a head pointer and return another pointer. Do not modify the input.
Solution
struct Node {
Node *prev; // previous node
Node *next; // next node
int data; // stored value
};
#include
#include \"List.h\" // std: #include
using namespace std;
typedef DataList ; // std: typedef list Data;
int main() {
Data k;
// back stuff
k.push_back(5);
k.push_back(6);
cout << k.back() << endl;
k.pop_back();
// front stuff
k.push_front(4);
k.push_front(3);
cout << k.front() << endl;
k.pop_front();
// forward iterator
Data::iterator pos;
for (pos = k.begin(); pos != k.end(); ++pos)
cout << *pos << endl;
// output and delete list
while (!k.empty()) {
cout << k.front() << endl;
k.pop_front();
}
k.push_front(5);
k.push_front(6);
// remove and erase
k.remove(5);
pos = k.begin();
k.erase(pos);
k.push_front(5);
k.push_front(6);
// copy constructor
Data l = k;
// assignment operator
Data m;
m = k;
return 0;
}
// List.h
struct Node;
classIterator List;
class List {
public:
typedef ListIterator iterator;
// constructor
List();
// destructor
virtual ~List();
// copy constructor
List(const List& k);
// assignment operator
List& operator=(const List& k);
// insert value in front of list
void push_front(double data);
// insert value in back of list
void push_back(double data);
// delete value from front of list
void pop_front();
// delete value from back of list
void pop_back();
// return value on front of list
double front() const;
// return value on back of list
double back() const;
// delete value specified by iterator
void erase(const iterator& i);
// delete all nodes with specified value
void remove(double data);
// return true if list is empty
bool empty() const;
// return reference to first element in list
iterator begin() const;
// return reference to one past last element in list
iterator end() const;
private:
Node *head; // head of list
};
class ListIterator {
public:
// default constructor
ListIterator() {
i = 0;
}
// construct iterator for given pointer (used for begin/end)
ListIterator(Node *p) {
i = p;
}
// convert iterator to Node*
operator Node*() const {
return i;
}
// test two iterators for not equal
bool operator!=(const ListIterator& k) const {
return i != k.i;
}
// preincrement operator
ListIterator& operator++() {
i = i->next;
return *this;
}
// return value associated with iterator
double& operator*() const {
return i->data;
}
private:
Node *i; // current value of iterator
};
list.cpp
// delete list
static void deleteList(Node *head) {
Node *p = head->next;
while (p != head) {
Node *next = p->next;
delete p;
p = next;
}
delete head;
}
// copy list
static void copyList(const Node *from, Node *&to) {
// create dummy header
to = new Node;
to->next = to->prev = to;
// copy nodes
for (Node *p = from->next; p != from; p = p->next) {
Node *t = new Node;
t.
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.
Javai have to make a method that takes a linked list and then retu.pdfstopgolook
Java
i have to make a method that takes a linked list and then returns a new linked list that is the
reverse of the original
this is the starting code
/**
* LinkedList lab.
* @author Emma Cheney
* @version 10/2/23
*/
public class LinkedList {
/**
* Internal Node class used for the linked list.
*/
public class Node {
String key;
int value;
Node next;
/**
* Node Constructor.
* @param key The Key
* @param value The Value
*/
public Node(String key, int value) {
this.key = key;
this.value = value;
}
}
private Node head;
private Node tail;
/**
* The default constructor.
*/
public LinkedList() {
head = null;
tail = null;
}
/**
* Add the key, value pair to the head of the linkedlist.
* @param key The Key
* @param val The Value
*
*/
public void addHead(String key, int val) {
Node n = new Node(key, val);
if (head == null) {
head = n;
tail = n;
} else {
n.next = head;
head = n;
}
}
/**
* Add the key, val pair to the tail of the linkedlist.
* @param key The Key
* @param val The Value
*/
public void addTail(String key, int val) {
Node n = new Node(key, val);
if (tail == null) {
head = n;
tail = n;
} else {
tail.next = n;
tail = n;
}
}
/**
* Returns the String format of the linkedlist.
* @return String The String format.
*/
public String toString() {
String ret = "";
Node curr = head;
while (curr != null) {
if (curr.next != null) {
ret += curr.key + ":" + curr.value + ", ";
} else {
ret += curr.key + ":" + curr.value;
}
curr = curr.next;
}
return ret;
}
/**
* Locate the Node in the linkedlist with the given key.
* @param key The key to find in the LinkedList
* @return Node Returns the Node with the given key or null if non-existent.
*/
private Node find(String key) {
Node curr = head;
while (curr != null) {
if (curr.key.equals(key)) {
return curr;
}
curr = curr.next;
}
return null;
} A static method called reversed that takes a LinkedList as a parameter and returns a new
LinkedList that is reversed. f; traverse through the input list (starting at the head). In order to
reverse the ordering, you need to add the current node's key and value onto the head of the new
list (addHead method). Do not change the input list or any values in it. Example (result in red)
//assumelistcontainsthesekeysandvalues://ie:6,bi:48,bi:73,bi:63LinkedList.reversed(list);bi:63,bi:
73,bi:48,ie:6.
package singlylinkedlist; public class Node { public String valu.pdfamazing2001
package singlylinkedlist;
public class Node {
public String value;
public Node next;
public Node(String value) {
this.value = value;
}
@Override
public String toString() {
return value;
}
}
SingleyLinkedList.java :
package singlylinkedlist;
import java.io.*;
import java.util.*;
/**
* Defines the interface for a singly-linked list.
*
*/
public interface SinglyLinkedList {
/**
* @return Reference to the first node. If the list is empty, this method
* returns null.
*/
public Node getFirst();
/**
* @return Reference to the last node . If the list is empty, this method
* returns null.
*/
public Node getLast();
/**
* @return Number of nodes in the list
*/
public int size();
/**
* @return true if the list has no nodes; false otherwise
*/
public boolean isEmpty();
/**
* Removes all nodes in the list.
*/
public void clear();
/**
* Inserts a new node with the given value after cursor.
*
* @param cursor
* The node to insert after. Set this to null to insert value as
the
* new first Node.
* @param value
* The value to insert
* @return a reference to the newly inserted Node
*/
public Node insert(Node cursor, String value);
/**
* Inserts a new node with the given value at the "end" of the list.
*
* @param value
* @return a reference to the newly inserted Node
*/
public Node append(String value);
/**
* Removes the node after the specified Node (cursor) from the list.
*
* @param cursor
* A reference to the Node to remove.
*/
public void removeAfter(Node cursor);
/**
* Returns a reference to the first Node containing the key, starting from
the
* given Node.
*
* @param start
* @param key
* @return a reference to the first Node containing the key
*/
public Node find(Node start, String key);
/**
* Prints the values of all the items in a list
*/
public void printWholeList();
}
SinglyLinkedTester.java:
package sbccunittest;
import static java.lang.Math.*;
import static java.lang.System.*;
import static org.apache.commons.lang3.StringUtils.*;
import static org.junit.Assert.*;
import static sbcc.Core.*;
import java.io.*;
import java.lang.reflect.*;
import java.nio.file.*;
import java.util.*;
import java.util.stream.*;
import org.apache.commons.lang3.*;
import org.junit.*;
import org.w3c.dom.ranges.*;
import sbcc.*;
import singlylinkedlist.*;
/**
* 09/16/2021
*
* @author sstrenn
*
*/
public class SinglyLinkedListTester {
public static String newline = System.getProperty("line.separator");
public static int totalScore = 0;
public static int extraCredit = 0;
public static boolean isZeroScore = false;
public static String scorePreamble = "";
@BeforeClass
public static void beforeTesting() {
totalScore = 0;
extraCredit = 0;
}
@AfterClass
public static void afterTesting() {
if (isZeroScore) {
totalScore = 0;
extraCredit = 0;
}
println(scorePreamble + "Estimated score (w/o late penalties, etc.) is:
" + totalScore + " out of 25.");
// If the project follows the naming convention, save the results in a
folder on
// the desktop. (Alex Kohanim)
try {
String directory =
substri.
So I have this code(StackInAllSocks) and I implemented the method but.pdfaksahnan
So I have this code( StackInAllSocks ) and I implemented the method but I can't seem to figure
out why there isn't anything showing up on the console. It should pop,peek and push b using the
methods from the class called ArrayListTen . The ArrayListTen works fine and compiles the
tested code of Rigth# but for StackInAllSocks it doesn't complete at all. note that file
VodeDodeis not to be changed is just a Node storage area of the array list.
Did I implement the method on StackInAllSocks correctly? if so, should I not use the method
from the ArrayListTen .?
__________________________________________________________________________
: the code is : VodeDodeis
class VodeDode<T> {
private T data;
private VodeDode<T> next;
private VodeDode<T> prev;
public VodeDode(T data) {
this.data = data;
this.next = null;
this.prev = null;}
public T getData() {
return data;}
public void setData(T data) {
this.data = data;}
public VodeDode<T> getNext() {
return this.next;}
public void setNext(VodeDode<T> next) {
this.next = next;}
public VodeDode<T> getPrev() {
return this.prev;}
public void setPrev(VodeDode<T> prev) {
this.prev = prev;}
@Override
public String toString() {
return data.toString();}}
_________________________________________________________________________
CODE that works fine called ArrayListTen:
import java.util.Iterator;
public class ArrayListTen<T> implements Iterable<T> {
private VodeDode<T> head; //beginning of list
private VodeDode<T> tail; //end of list
private int size;
private VodeDode<T> new_item;
public ArrayListTen( ){
this.head = null;
this.tail = null;
this.size = 0;}
public int lenght() {
return size ;}
public T getBegin() {
if (this.head != null) {
return head.getData();}
else { return null;}}
public void addBegin(T value) {
VodeDode<T> newVodeDode =new VodeDode<T>(value);
if (this.head== null) {
head = newVodeDode;
tail =newVodeDode;}
else {VodeDode<T> temp = head;
head = newVodeDode;
head.setNext(temp);}
size++;}
public T removeBegin() {
if(this.head == null) {
return null;}
else {T current = head.getData();
if (tail == head) {
tail = null;
head = null;
} else {
head = head.getNext();
head.setPrev(null);}size--;
return current;}}
public T getEnd() {
if (tail != null) {
return tail.getData();
} else {
return null;}}
public void addEnd(T value) {
VodeDode<T> newVodeDode = new VodeDode<T>(value);
if (this.tail == null) {
head = newVodeDode;
tail = newVodeDode;
} else {
newVodeDode.setPrev(tail);
tail.setNext(newVodeDode);
tail = newVodeDode;}
size++;}
public T removeEnd() {
if(this.tail == null) {
return null;}
else {
T current = tail.getData();//was head.
if (head == tail) {
head = null;
tail = null;
} else {
tail = tail.getPrev();
tail.setNext(null);}
size--;
return current;}}
public T removeBN(T value) {
VodeDode<T> currVodeDode = head;
VodeDode<T> prevVodeDode = null;
while(currVodeDode != null){
if(currVodeDode.getData().equals(value)){
if(prevVodeDode != null){
prevVodeDode.setNext(currVodeDode.getNext());}
else{
head = curr.
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.
import java.util.Iterator; import java.util.NoSuchElementException; /** * An implementation
of MyList with a linked list (a longer exercise would be to * implement the List interface as is
done in the class java.util.LinkedList: * the source of the LinkedList class is available from Sun.
Check it out). */ public class MyLinkedList implements MyList { // A private class to
represent a Node in the linked list private class Node { public E item;
public Node next; // a convenient constructor public Node(E o) {
this.item = o; this.next = null; } } // The start of the linked
list private Node head; // The last Node in the linked list private Node tail;
// Number of elements in the list private int size; /** * Creates an empty list (this
constructor is not necessary) */ public MyLinkedList() { } /** *
Returns the number of elements in this list. */ public int size() { return size;
} /** * Returns true if this list contains no elements. */ public boolean
isEmpty() { return size == 0; } /** * Appends the specified element to
the end of this list */ public boolean add(E o) { Node n = new Node(o);
// If this is the first element in the list if (head == null) { head = n;
} else { // If the list is not empty, use tail tail.next = n;
} // update tail tail = n; // update size size++;
return true; } /** * Empties this List */ public void clear() {
// update head, tail and size head = tail = null; size = 0; } /**
* Returns the element at the specified position in this list. */ public E get(int index) {
if (index < 0 || index >= size) { throw new
IndexOutOfBoundsException(\"index = \" + index); } // Find it
Node n = head; for (int i = 0; i < index; i++) { n = n.next; }
return n.item; } /** * Returns the index of the specified element (-1 if
there is no match) */ public int indexOf(Object o) { // If o is null
int index = 0; Node p = head; if (o == null) // look for a null element in the
list { while (p != null) { if (p.item == null) {
return index; } index++;
p = p.next; } } else // o is an object (use equals) {
while (p != null) { if (o.equals(p.item)) { return
index; } index++; p = p.next;
} } // if we get here, o is not in the list return -1; }
/** * Returns true if this list contains the specified element. */ public boolean
contains(Object o) { // easy with indexOf return indexOf(o) != -1; }
/** * Removes the element in the List at position index */ public boolean
remove(int index) { if (index < 0 || index >= size) { throw new
IndexOutOfBoundsException(\"index = \" + index); } // Find the
corresponding node Node prev = null, p = head; for (int i = 0; i < index; i++)
{ prev = p; p = p.next; } // Remove it
// Special case for the first node if (p == head) { head = head.next;
} else { prev.next = p.next; } // If the last node has been
removed, update tail if (p == tail) { tail = prev; } //
update size size--; return true; } /** * Removes the element
in the List at position index */ public boolean remove(Object o) { // easy
with indexOf and remove int index = i.
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.
Tree Traversals A tree traversal is the process of visiting.pdfajayadinathcomputers
Tree Traversals
A tree traversal is the process of "visiting" each node of a tree in some particular order. For a
binary search tree, we can talk about an inorder traversal and a preorder traversal. For this
assignment you are to implement both of these traversals in the code that was started in class.
File bstree.h contains the BSTree class that was developed during class (with the addition of
comments which were omitted by your instructor due to time constraints). The class contains two
inorder functions, one public and one private, and two preorder functions, also one public and one
private. As was the case with other functions implemented for this class, the public versions of
these functions simply call the private versions passing the root node (pointer) as a parameter.
The private versions carry out their actions on the subtree rooted at the given node.
The code provided in bstree.h is missing the implementations for the private inorder and preorder
functions. The coding part of this assignment is to implement these two functions.
When completed, the test program provided should produce the following output:
Values stored in the tree are:
bird
cat
deer
dog
giraffe
groundhog
horse
snake
turtle
The structure of the tree is as follows:
dog
-bird
--cat
---deer
-turtle
--giraffe
---snake
----groundhog
-----horse
Copied!
Written Part
In addition to the coding noted above, give an analysis of all public member functions of the class,
including all constructors, the destructor, and the overload of the assignment operator. For your
analysis you may assume a well-balanced tree (whereas a lopsided tree might lead to a different
analysis).
bstree.h
#pragma once
// A Binary Search Tree implementation.
template <typename T>
class BSTree {
private:
// A node in the tree. Each node has pointers to its left and right nodes
// as well as its parent. When a node is created, the parent and data item
// must be provided.
class node {
public:
T data;
node* left;
node* right;
node* parent;
node (const T& d, node* p) {
parent = p;
data = d;
left = right = nullptr;
}
};
// Pointer to the root node. Initially this is null for an empty tree.
node* root;
// Copy the subtree of another BSTree object into this object. Used by
// the copy constructor and assignment operator.
void copy (node* p) {
if (p) { // If p points to a node...
insert(p->data); // Insert data item
copy(p->left); // Copy the left subtree
copy(p->right); // Copy the right subtree
}
}
// Destroy a node and all nodes in both subtrees. Called by the
// destructor.
void destroy (node* p) {
if (p) { // If p is not null...
destroy(p->left); // Destroy the left subtree
destroy(p->right); // Destroy the right subtree
delete p; // Destroy the node
}
}
// Helper function to determine if a data value is contained in the tree.
// Takes the data value being searched and a pointer to the node in the
// tree. Returns pointer to node in which data item is found, a null
// pointer otherwise.
node* find (const T& .
AvlTree.h
#ifndef AVL_TREE_H
#define AVL_TREE_H
#include "dsexceptions.h"
#include <iostream> // For NULL
#include <queue> // For level order printout
#include <vector>
#include <algorithm> // For max() function
using namespace std;
// AvlTree class
//
// CONSTRUCTION: with ITEM_NOT_FOUND object used to signal failed finds
//
// ******************PUBLIC OPERATIONS*********************
// Programming Assignment Part I
// bool empty( ) --> Test for empty tree @ root
// int size( ) --> Quantity of elements in tree
// int height( ) --> Height of the tree (null == -1)
// void insert( x ) --> Insert x
// void insert( vector<T> ) --> Insert whole vector of values
// void remove( x ) --> Remove x (unimplemented)
// bool contains( x ) --> Return true if x is present
// Comparable findMin( ) --> Return smallest item
// Comparable findMax( ) --> Return largest item
// boolean isEmpty( ) --> Return true if empty; else false
// void printTree( ) --> Print tree in sorted (in) order
// void printPreOrder( ) --> Print tree in pre order
// void printPostOrder( ) --> Print tree in post order
// void printInOrder( ) --> Print tree in *in* order
// Programming Assignment Part II (microassignment)
// void makeEmpty( ) --> Remove and delete all items
// void ~AvlTree( ) --> Big Five Destructor
// AvlTree(const AvlTree &other) --> BigFive Copy Constructor
// AvlTree(const AvlTree &&other) --> BigFive Move Constructor
// AvlTree &operator= ( AvlTree & other ) --> Big Five Copy *assignment* operator
// AvlTree &operator= ( AvlTree && other ) --> Big Five Move *assignment* operator
// void printLevelOrder( ) --> Print tree in LEVEL order :-)
// ******************ERRORS********************************
// Throws UnderflowException as warranted
template <typename Comparable>
class AvlTree
{
public:
/**
* Basic constructor for an empty tree
*/
AvlTree( ) : root( NULL )
{
//cout << " [d] AvlTree constructor called. " << endl;
}
/**
* Vector of data initializer (needed for move= operator rvalue)
*/
AvlTree( vector<Comparable> vals ) : root( NULL )
{
insert(vals);
}
//*******************************************************************************************
// START AVL TREES PART II - TODO: Implement
// Other functions to look for include: clone, makeEmpty, printLevelOrder
/**
* Destroy contents of the AvlTree object - Big Five Destructor
*/
~AvlTree( )
{
//cout << " [d] AvlTree Destructor called. " << endl;
// Empty out the AVL Tree and destroy all nodes (makeEmpty?)
}
/**
* Copy other to new object - Big Five Copy Constructor
*/
AvlTree( const AvlTree &other ) : root( NULL )
{
cout << " [d] Copy Constructor Called." << endl;
// Copy contents of other to ourselves (maybe clone?)
// Get a deep copy of other's tree
}
/* ...
Data Structures in C++I am really new to C++, so links are really .pdfrohit219406
Data Structures in C++
I am really new to C++, so links are really hard topic for me. It would be nice if you can provide
explanations of what doubly linked lists are and of some of you steps... Thank you
In this assignment, you will implement a doubly-linked list class, together with some list
operations. To make things easier, you’ll implement a list of int, rather than a template class.
Solution
A variable helps us to identify the data. For ex: int a = 5; Here 5 is identified through variable a.
Now, if we have collection of integers, we need some representation to identify them. We call it
array. For ex: int arr[5]
This array is nothing but a Data Structure.
So, a Data Structure is a way to group the data.
There are many Data Structures available like Arrays, Linked List, Doubly-Linked list, Stack,
Queue, etc.
Doubly-Linked list are the ones where you can traverse from the current node both in left and
right directions.
Why so many different types of Data Structures are required ?
Answer is very simple, grouping of data, storage of data and accessing the data is different.
For example, in case of Arrays we store all the data in contiguous locations.
What if we are not able to store the data in contiguous locations because we have huge data.
Answer is go for Linked List/Doubly-Linked list.
Here we can store the data anywhere and link the data through pointers.
I will try to provide comments for the code you have given. May be this can help you.
#pragma once
/*
dlist.h
Doubly-linked lists of ints
*/
#include
class dlist {
public:
dlist() { }
// Here we are creating a NODE, it has a integer value and two pointers.
// One pointer is to move to next node and other to go back to previous node.
struct node {
int value;
node* next;
node* prev;
};
// To return head pointer, i.e. start of the Doubly-Linked list.
node* head() const { return _head; }
// To return Tail pointer, i.e. end of the Doubly-Linked list.
node* tail() const { return _tail; }
// **** Implement ALL the following methods ****
// Returns the node at a particular index (0 is the head).
node* at(int index){
int cnt = 0;
struct node* tmp = head();
while(tmp!=NULL)
{
if (cnt+1 == index)
return tmp;
tmp = tmp->next;
}
}
// Insert a new value, after an existing one
void insert(node *previous, int value){
// check if the given previous is NULL
if (previous == NULL)
{
printf(\"the given previous node cannot be NULL\");
return;
}
// allocate new node
struct node* new_node =(struct node*) malloc(sizeof(struct node));
// put in the data
new_node->data = new_data;
// Make next of new node as next of previous
new_node->next = previous->next;
// Make the next of previous as new_node
previous->next = new_node;
// Make previous as previous of new_node
new_node->prev = previous;
// Change previous of new_node\'s next node
if (new_node->next != NULL)
new_node->next->prev = new_node;
}
// Delete the given node
void del(node* which){
struct node* head_ref = head();
/* base case */
if(*head_ref == NUL.
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.
How to do the main method for this programBinaryNode.javapublic.pdffeelingcomputors
How to do the main method for this program?
BinaryNode.java
public class BinaryNode
implements Parent{
/** The item associated with this node. */
private E item;
/** The node at the root of the left subtree. */
private BinaryNode left;
/** The node at the root of the right subtree. */
private BinaryNode right;
/** Put item in a leaf node. */
public BinaryNode(E item) {
this.item = item;
// left and right are set to null by default
}
/** no-argument constructor sets everything to null */
public BinaryNode() {
item = null;
left = null;
right = null;
}
/** Put item in a node with the specified subtrees. */
public BinaryNode(E item, BinaryNode left,
BinaryNode right) {
this.item = item;
this.left = left;
this.right = right;
}
/** Put item in a node with the specified subtrees. */
public BinaryNode getChild(int direction) {
if (direction < 0) {
return left;
} else {
return right;
}
}
/** Return the item associated with this node. */
public E getItem() {
return item;
}
/** Return the root of the left subtree. */
public BinaryNode getLeft() {
return left;
}
/** Return the root of the right subtree. */
public BinaryNode getRight() {
return right;
}
/** Return true if this is a leaf. */
public boolean isLeaf() {
return (left == null) && (right == null);
}
/** Replace the item associated with this node. */
public void setItem(E item) {
this.item = item;
}
/** Replace the left subtree with the one rooted at left. */
public void setLeft(BinaryNode left) {
this.left = left;
}
/** Replace the right subtree with the one rooted at right. */
public void setRight(BinaryNode right) {
this.right = right;
}
public void setChild(int direction, BinaryNode child) {
if (direction < 0) {
left = child;
} else {
right = child;
}
}
/**
* Return the String representation of the tree rooted at this node
* traversed preorder.
**/
public String toStringPreorder() {
String result = \"\";
result += item;
if (left != null) {
result += left.toStringPreorder();
}
if (right != null) {
result += right.toStringPreorder();
}
return result;
}
/** Return a String representation of the tree rooted at this node
* traversed inorder.
**/
public String toStringInOrder() {
String result = \"\";
if (left != null) {
result += left.toStringInOrder();
}
result += item;
if (right != null) {
result += right.toStringInOrder();
}
return result;
}
/** Return a String representation of the tree rooted at this node,
* traversed postorder.
**/
public String toStringPostorder() {
String result = \"\";
if (left != null) {
result += left.toStringPostorder();
}
if (right != null) {
result += right.toStringPostorder();
}
result += item;
return result;
}
/**
* Return a String representation of the tree rooted at this node,
* traversed level order.
**/
public String toStringLevelOrder() {
String result = \"\";
Queue> q = new ArrayQueue>();
q.add (this);
while (!(q.isEmpty())) {
BinaryNode node = q.remove ();
result += node.item;
if (node.left != null) {
q.add(node.left);
}
if (node.right != null) {
q.add(node..
The LinkedList1 class implements a Linked list. class.pdfmalavshah9013
/**
The LinkedList1 class implements a Linked list.
*/
class LinkedList1
{
/**
The Node class stores a list element
and a reference to the next node.
*/
private class Node
{
String value;
Node next;
/**
Constructor.
@param val The element to store in the node.
@param n The reference to the successor node.
*/
Node(String val, Node n)
{
value = val;
next = n;
}
/**
Constructor.
@param val The element to store in the node.
*/
Node(String val)
{
// Call the other (sister) constructor.
this(val, null);
}
}
private Node first; // list head
private Node last; // last element in list
/**
Constructor.
*/
public LinkedList1()
{
first = null;
last = null;
}
/**
The isEmpty method checks to see
if the list is empty.
@return true if list is empty,
false otherwise.
*/
public boolean isEmpty()
{
return first == null;
}
/**
The size method returns the length of the list.
@return The number of elements in the list.
*/
public int size()
{
int count = 0;
Node p = first;
while (p != null)
{
// There is an element at p
count ++;
p = p.next;
}
return count;
}
/**
The add method adds an element to
the end of the list.
@param e The value to add to the
end of the list.
*/
public void add(String e)
{
if (isEmpty())
{
first = new Node(e);
last = first;
}
else
{
// Add to end of existing list
last.next = new Node(e);
last = last.next;
}
}
/**
The add method adds an element at a position.
@param e The element to add to the list.
@param index The position at which to add
the element.
@exception IndexOutOfBoundsException When
index is out of bounds.
*/
public void add(int index, String e)
{
if (index < 0 || index > size())
{
String message = String.valueOf(index);
throw new IndexOutOfBoundsException(message);
}
// Index is at least 0
if (index == 0)
{
// New element goes at beginning
first = new Node(e, first);
if (last == null)
last = first;
return;
}
// Set a reference pred to point to the node that
// will be the predecessor of the new node
Node pred = first;
for (int k = 1; k <= index - 1; k++)
{
pred = pred.next;
}
// Splice in a node containing the new element
pred.next = new Node(e, pred.next);
// Is there a new last element ?
if (pred.next.next == null)
last = pred.next;
}
/**
The toString method computes the string
representation of the list.
@return The string form of the list.
*/
public String toString()
{
StringBuilder strBuilder = new StringBuilder();
// Use p to walk down the linked list
Node p = first;
while (p != null)
{
strBuilder.append(p.value + \"\ \");
p = p.next;
}
return strBuilder.toString();
}
/**
The remove method removes the element at an index.
@param index The index of the element to remove.
@return The element removed.
@exception IndexOutOfBoundsException When index is
out of bounds.
*/
public String remove(int index)
{
if (index < 0 || index >= size())
{
String message = String.valueOf(index);
throw new IndexOutOfBoundsException(message);
}
String element; // The element to return
if (index == 0)
{
// Removal of first item in the list
element.
Describe an algorithm for concatenating two singly linked lists L and.pdfdeepak596396
Dataset:
https://docs.google.com/spreadsheets/d/1NxuGt4LJ3ofi2PaWLWpAl90JmfqMKcGV/edit?usp=sharing&ouid=111109979069524025260&rtpof=true&sd=true
Q1) What is the average tenure of those customers of the telecom operator who are still with the
company as a customer and also those who have stopped using the services provided by the
company? (1 mark)
Here, churn = 'No' means that the customer is currently associated with the company, and churn
= 'Yes' means that the customer has stopped using the services provided by the company.
Q2)What is the monthly average revenue generated by the customers who are with the company
and also those who have left? (1 mark)
Q3) Find the percentage of churn and non-churn customers for each category of the following
services: (4 marks)
-MultipleLines
-PaperlessBilling
-OnlineSecurity
-OnlineBackup
-DeviceProtection
-TechSupport
-StreamingTV
-StreamingMovies.
Problem I. As shown in the pedigree below, a pair of first cousins (.pdfsivakumar19831
Problem I. As shown in the pedigree below, a pair of first cousins (I and K) marry an unrelated
pair of first cousins (J and L). Their children M and N produce child O.
Q1. Calculate the inbreeding coefficient (f) of O (express answers to Q1 and Q3 to three decimal
places). Assume that f= 0 for all ancestors. (Hint: To help you out, I have shaded individuals
who cannot contribute to autozygosity.) To show your work, use the letter names to indicate each
path/loop that contributes to autozygosity. For example: path 1 = M-I-E…
Q2. Interpret your result. What does this value of f indicate?
Q3. Recalculate f for child O when f=1/2 for great-great grandmother D (f=0 for all other
ancestors). Hint: After you have calculated all the loops above, you’ll adjust just the loop that
includes ancester D to account for her ancestral inbreeding using the formula presented in class
(and text). B 0271 M H K E
Solution
Path 1:
· O-M-I-E-A-F-K-N-O
· O-M-I-E-B-F-K-N-O
So, the probability that a copy of gene in A makes the way down to O via E and a copy of gene
in B makes the way down to O via F =(½)n = (½)7=0.00781. Here n= node=7
Path 2:
· O-N-L-H-D-G-J-M-O
· O-N-L-H-C-G-J-M-O
Similarly, like the first one the total probability in path 2 will be same that is 0.00781.
Thus inbreeding co-efficient = 0.00781+0.00781=0.01562.
2. Generally, the higher the level of inbreeding closer the coefficient of relationship approaches a
value of 1 and approaches a value of 0 for individuals with remote common ancestors.
As here the value of inbreeding co-efficient is approximately 0 so we can conclude that
1. the common ancestors are not inbred.
2. O has remote common ancestors means they are distantly related.
3. When a common ancestor is itself inbred the inbreeding coefficient is = (1/2)n (1+ inbreeding
co-efficient of common ancestor) ,
The probability that a copy of gene in D makes the way to O = (1/2)7 = 0.00781
Therefore, inbreeding co-efficient is = 0.00781 * (1 + 1/2) =0.01172.
Points are assigned both on the correctness of the answer and the com.pdfsivakumar19831
Points are assigned both on the correctness of the answer and the completeness of the problem -
show all givens, state all assumptions, show all calculations. 1. Transportation affects society in
many ways and is frequently in the news. Find a transportation news article for a local, regional,
or national source (newspaper, credible internet site, etc.). Provide a link to the article and
summarize the article and explain the importance.
Solution
Hello,
As stated I am providing you with a link to the *.Pdf file regarding Transportation and its role in
society.
https://nptel.ac.in/courses/105101087/downloads/Lec-3.pdf
This is a very credible source.
Transportation is a non separable part of any society. It exhibits a very close relation to the style
of life, the range and location of activities and the goods and services which will be available for
consumption. Advances in transportation has made possible changes in the way of living and the
way in which societies are organized and therefore have a great inuence in the development of
civilizations. This chapter conveys an understanding of the importance of transportation in the
modern society by presenting selected characteristics of existing transportation systems, their use
and relationships to other human activities. Transportation is responsible for the development of
civilizations from very old times by meeting travel requirement of people and transport
requirement of goods. Such movement has changed the way people live and travel. In developed
and developing nations, a large fraction of people travel daily for work,shopping and social
reasons. But transport also consumes a lot of resources like time,fuel, materials and land..
More Related Content
Similar to Objective Binary Search Tree traversal (2 points)Use traversal.pp.pdf
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.
Javai have to make a method that takes a linked list and then retu.pdfstopgolook
Java
i have to make a method that takes a linked list and then returns a new linked list that is the
reverse of the original
this is the starting code
/**
* LinkedList lab.
* @author Emma Cheney
* @version 10/2/23
*/
public class LinkedList {
/**
* Internal Node class used for the linked list.
*/
public class Node {
String key;
int value;
Node next;
/**
* Node Constructor.
* @param key The Key
* @param value The Value
*/
public Node(String key, int value) {
this.key = key;
this.value = value;
}
}
private Node head;
private Node tail;
/**
* The default constructor.
*/
public LinkedList() {
head = null;
tail = null;
}
/**
* Add the key, value pair to the head of the linkedlist.
* @param key The Key
* @param val The Value
*
*/
public void addHead(String key, int val) {
Node n = new Node(key, val);
if (head == null) {
head = n;
tail = n;
} else {
n.next = head;
head = n;
}
}
/**
* Add the key, val pair to the tail of the linkedlist.
* @param key The Key
* @param val The Value
*/
public void addTail(String key, int val) {
Node n = new Node(key, val);
if (tail == null) {
head = n;
tail = n;
} else {
tail.next = n;
tail = n;
}
}
/**
* Returns the String format of the linkedlist.
* @return String The String format.
*/
public String toString() {
String ret = "";
Node curr = head;
while (curr != null) {
if (curr.next != null) {
ret += curr.key + ":" + curr.value + ", ";
} else {
ret += curr.key + ":" + curr.value;
}
curr = curr.next;
}
return ret;
}
/**
* Locate the Node in the linkedlist with the given key.
* @param key The key to find in the LinkedList
* @return Node Returns the Node with the given key or null if non-existent.
*/
private Node find(String key) {
Node curr = head;
while (curr != null) {
if (curr.key.equals(key)) {
return curr;
}
curr = curr.next;
}
return null;
} A static method called reversed that takes a LinkedList as a parameter and returns a new
LinkedList that is reversed. f; traverse through the input list (starting at the head). In order to
reverse the ordering, you need to add the current node's key and value onto the head of the new
list (addHead method). Do not change the input list or any values in it. Example (result in red)
//assumelistcontainsthesekeysandvalues://ie:6,bi:48,bi:73,bi:63LinkedList.reversed(list);bi:63,bi:
73,bi:48,ie:6.
package singlylinkedlist; public class Node { public String valu.pdfamazing2001
package singlylinkedlist;
public class Node {
public String value;
public Node next;
public Node(String value) {
this.value = value;
}
@Override
public String toString() {
return value;
}
}
SingleyLinkedList.java :
package singlylinkedlist;
import java.io.*;
import java.util.*;
/**
* Defines the interface for a singly-linked list.
*
*/
public interface SinglyLinkedList {
/**
* @return Reference to the first node. If the list is empty, this method
* returns null.
*/
public Node getFirst();
/**
* @return Reference to the last node . If the list is empty, this method
* returns null.
*/
public Node getLast();
/**
* @return Number of nodes in the list
*/
public int size();
/**
* @return true if the list has no nodes; false otherwise
*/
public boolean isEmpty();
/**
* Removes all nodes in the list.
*/
public void clear();
/**
* Inserts a new node with the given value after cursor.
*
* @param cursor
* The node to insert after. Set this to null to insert value as
the
* new first Node.
* @param value
* The value to insert
* @return a reference to the newly inserted Node
*/
public Node insert(Node cursor, String value);
/**
* Inserts a new node with the given value at the "end" of the list.
*
* @param value
* @return a reference to the newly inserted Node
*/
public Node append(String value);
/**
* Removes the node after the specified Node (cursor) from the list.
*
* @param cursor
* A reference to the Node to remove.
*/
public void removeAfter(Node cursor);
/**
* Returns a reference to the first Node containing the key, starting from
the
* given Node.
*
* @param start
* @param key
* @return a reference to the first Node containing the key
*/
public Node find(Node start, String key);
/**
* Prints the values of all the items in a list
*/
public void printWholeList();
}
SinglyLinkedTester.java:
package sbccunittest;
import static java.lang.Math.*;
import static java.lang.System.*;
import static org.apache.commons.lang3.StringUtils.*;
import static org.junit.Assert.*;
import static sbcc.Core.*;
import java.io.*;
import java.lang.reflect.*;
import java.nio.file.*;
import java.util.*;
import java.util.stream.*;
import org.apache.commons.lang3.*;
import org.junit.*;
import org.w3c.dom.ranges.*;
import sbcc.*;
import singlylinkedlist.*;
/**
* 09/16/2021
*
* @author sstrenn
*
*/
public class SinglyLinkedListTester {
public static String newline = System.getProperty("line.separator");
public static int totalScore = 0;
public static int extraCredit = 0;
public static boolean isZeroScore = false;
public static String scorePreamble = "";
@BeforeClass
public static void beforeTesting() {
totalScore = 0;
extraCredit = 0;
}
@AfterClass
public static void afterTesting() {
if (isZeroScore) {
totalScore = 0;
extraCredit = 0;
}
println(scorePreamble + "Estimated score (w/o late penalties, etc.) is:
" + totalScore + " out of 25.");
// If the project follows the naming convention, save the results in a
folder on
// the desktop. (Alex Kohanim)
try {
String directory =
substri.
So I have this code(StackInAllSocks) and I implemented the method but.pdfaksahnan
So I have this code( StackInAllSocks ) and I implemented the method but I can't seem to figure
out why there isn't anything showing up on the console. It should pop,peek and push b using the
methods from the class called ArrayListTen . The ArrayListTen works fine and compiles the
tested code of Rigth# but for StackInAllSocks it doesn't complete at all. note that file
VodeDodeis not to be changed is just a Node storage area of the array list.
Did I implement the method on StackInAllSocks correctly? if so, should I not use the method
from the ArrayListTen .?
__________________________________________________________________________
: the code is : VodeDodeis
class VodeDode<T> {
private T data;
private VodeDode<T> next;
private VodeDode<T> prev;
public VodeDode(T data) {
this.data = data;
this.next = null;
this.prev = null;}
public T getData() {
return data;}
public void setData(T data) {
this.data = data;}
public VodeDode<T> getNext() {
return this.next;}
public void setNext(VodeDode<T> next) {
this.next = next;}
public VodeDode<T> getPrev() {
return this.prev;}
public void setPrev(VodeDode<T> prev) {
this.prev = prev;}
@Override
public String toString() {
return data.toString();}}
_________________________________________________________________________
CODE that works fine called ArrayListTen:
import java.util.Iterator;
public class ArrayListTen<T> implements Iterable<T> {
private VodeDode<T> head; //beginning of list
private VodeDode<T> tail; //end of list
private int size;
private VodeDode<T> new_item;
public ArrayListTen( ){
this.head = null;
this.tail = null;
this.size = 0;}
public int lenght() {
return size ;}
public T getBegin() {
if (this.head != null) {
return head.getData();}
else { return null;}}
public void addBegin(T value) {
VodeDode<T> newVodeDode =new VodeDode<T>(value);
if (this.head== null) {
head = newVodeDode;
tail =newVodeDode;}
else {VodeDode<T> temp = head;
head = newVodeDode;
head.setNext(temp);}
size++;}
public T removeBegin() {
if(this.head == null) {
return null;}
else {T current = head.getData();
if (tail == head) {
tail = null;
head = null;
} else {
head = head.getNext();
head.setPrev(null);}size--;
return current;}}
public T getEnd() {
if (tail != null) {
return tail.getData();
} else {
return null;}}
public void addEnd(T value) {
VodeDode<T> newVodeDode = new VodeDode<T>(value);
if (this.tail == null) {
head = newVodeDode;
tail = newVodeDode;
} else {
newVodeDode.setPrev(tail);
tail.setNext(newVodeDode);
tail = newVodeDode;}
size++;}
public T removeEnd() {
if(this.tail == null) {
return null;}
else {
T current = tail.getData();//was head.
if (head == tail) {
head = null;
tail = null;
} else {
tail = tail.getPrev();
tail.setNext(null);}
size--;
return current;}}
public T removeBN(T value) {
VodeDode<T> currVodeDode = head;
VodeDode<T> prevVodeDode = null;
while(currVodeDode != null){
if(currVodeDode.getData().equals(value)){
if(prevVodeDode != null){
prevVodeDode.setNext(currVodeDode.getNext());}
else{
head = curr.
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.
import java.util.Iterator; import java.util.NoSuchElementException; /** * An implementation
of MyList with a linked list (a longer exercise would be to * implement the List interface as is
done in the class java.util.LinkedList: * the source of the LinkedList class is available from Sun.
Check it out). */ public class MyLinkedList implements MyList { // A private class to
represent a Node in the linked list private class Node { public E item;
public Node next; // a convenient constructor public Node(E o) {
this.item = o; this.next = null; } } // The start of the linked
list private Node head; // The last Node in the linked list private Node tail;
// Number of elements in the list private int size; /** * Creates an empty list (this
constructor is not necessary) */ public MyLinkedList() { } /** *
Returns the number of elements in this list. */ public int size() { return size;
} /** * Returns true if this list contains no elements. */ public boolean
isEmpty() { return size == 0; } /** * Appends the specified element to
the end of this list */ public boolean add(E o) { Node n = new Node(o);
// If this is the first element in the list if (head == null) { head = n;
} else { // If the list is not empty, use tail tail.next = n;
} // update tail tail = n; // update size size++;
return true; } /** * Empties this List */ public void clear() {
// update head, tail and size head = tail = null; size = 0; } /**
* Returns the element at the specified position in this list. */ public E get(int index) {
if (index < 0 || index >= size) { throw new
IndexOutOfBoundsException(\"index = \" + index); } // Find it
Node n = head; for (int i = 0; i < index; i++) { n = n.next; }
return n.item; } /** * Returns the index of the specified element (-1 if
there is no match) */ public int indexOf(Object o) { // If o is null
int index = 0; Node p = head; if (o == null) // look for a null element in the
list { while (p != null) { if (p.item == null) {
return index; } index++;
p = p.next; } } else // o is an object (use equals) {
while (p != null) { if (o.equals(p.item)) { return
index; } index++; p = p.next;
} } // if we get here, o is not in the list return -1; }
/** * Returns true if this list contains the specified element. */ public boolean
contains(Object o) { // easy with indexOf return indexOf(o) != -1; }
/** * Removes the element in the List at position index */ public boolean
remove(int index) { if (index < 0 || index >= size) { throw new
IndexOutOfBoundsException(\"index = \" + index); } // Find the
corresponding node Node prev = null, p = head; for (int i = 0; i < index; i++)
{ prev = p; p = p.next; } // Remove it
// Special case for the first node if (p == head) { head = head.next;
} else { prev.next = p.next; } // If the last node has been
removed, update tail if (p == tail) { tail = prev; } //
update size size--; return true; } /** * Removes the element
in the List at position index */ public boolean remove(Object o) { // easy
with indexOf and remove int index = i.
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.
Tree Traversals A tree traversal is the process of visiting.pdfajayadinathcomputers
Tree Traversals
A tree traversal is the process of "visiting" each node of a tree in some particular order. For a
binary search tree, we can talk about an inorder traversal and a preorder traversal. For this
assignment you are to implement both of these traversals in the code that was started in class.
File bstree.h contains the BSTree class that was developed during class (with the addition of
comments which were omitted by your instructor due to time constraints). The class contains two
inorder functions, one public and one private, and two preorder functions, also one public and one
private. As was the case with other functions implemented for this class, the public versions of
these functions simply call the private versions passing the root node (pointer) as a parameter.
The private versions carry out their actions on the subtree rooted at the given node.
The code provided in bstree.h is missing the implementations for the private inorder and preorder
functions. The coding part of this assignment is to implement these two functions.
When completed, the test program provided should produce the following output:
Values stored in the tree are:
bird
cat
deer
dog
giraffe
groundhog
horse
snake
turtle
The structure of the tree is as follows:
dog
-bird
--cat
---deer
-turtle
--giraffe
---snake
----groundhog
-----horse
Copied!
Written Part
In addition to the coding noted above, give an analysis of all public member functions of the class,
including all constructors, the destructor, and the overload of the assignment operator. For your
analysis you may assume a well-balanced tree (whereas a lopsided tree might lead to a different
analysis).
bstree.h
#pragma once
// A Binary Search Tree implementation.
template <typename T>
class BSTree {
private:
// A node in the tree. Each node has pointers to its left and right nodes
// as well as its parent. When a node is created, the parent and data item
// must be provided.
class node {
public:
T data;
node* left;
node* right;
node* parent;
node (const T& d, node* p) {
parent = p;
data = d;
left = right = nullptr;
}
};
// Pointer to the root node. Initially this is null for an empty tree.
node* root;
// Copy the subtree of another BSTree object into this object. Used by
// the copy constructor and assignment operator.
void copy (node* p) {
if (p) { // If p points to a node...
insert(p->data); // Insert data item
copy(p->left); // Copy the left subtree
copy(p->right); // Copy the right subtree
}
}
// Destroy a node and all nodes in both subtrees. Called by the
// destructor.
void destroy (node* p) {
if (p) { // If p is not null...
destroy(p->left); // Destroy the left subtree
destroy(p->right); // Destroy the right subtree
delete p; // Destroy the node
}
}
// Helper function to determine if a data value is contained in the tree.
// Takes the data value being searched and a pointer to the node in the
// tree. Returns pointer to node in which data item is found, a null
// pointer otherwise.
node* find (const T& .
AvlTree.h
#ifndef AVL_TREE_H
#define AVL_TREE_H
#include "dsexceptions.h"
#include <iostream> // For NULL
#include <queue> // For level order printout
#include <vector>
#include <algorithm> // For max() function
using namespace std;
// AvlTree class
//
// CONSTRUCTION: with ITEM_NOT_FOUND object used to signal failed finds
//
// ******************PUBLIC OPERATIONS*********************
// Programming Assignment Part I
// bool empty( ) --> Test for empty tree @ root
// int size( ) --> Quantity of elements in tree
// int height( ) --> Height of the tree (null == -1)
// void insert( x ) --> Insert x
// void insert( vector<T> ) --> Insert whole vector of values
// void remove( x ) --> Remove x (unimplemented)
// bool contains( x ) --> Return true if x is present
// Comparable findMin( ) --> Return smallest item
// Comparable findMax( ) --> Return largest item
// boolean isEmpty( ) --> Return true if empty; else false
// void printTree( ) --> Print tree in sorted (in) order
// void printPreOrder( ) --> Print tree in pre order
// void printPostOrder( ) --> Print tree in post order
// void printInOrder( ) --> Print tree in *in* order
// Programming Assignment Part II (microassignment)
// void makeEmpty( ) --> Remove and delete all items
// void ~AvlTree( ) --> Big Five Destructor
// AvlTree(const AvlTree &other) --> BigFive Copy Constructor
// AvlTree(const AvlTree &&other) --> BigFive Move Constructor
// AvlTree &operator= ( AvlTree & other ) --> Big Five Copy *assignment* operator
// AvlTree &operator= ( AvlTree && other ) --> Big Five Move *assignment* operator
// void printLevelOrder( ) --> Print tree in LEVEL order :-)
// ******************ERRORS********************************
// Throws UnderflowException as warranted
template <typename Comparable>
class AvlTree
{
public:
/**
* Basic constructor for an empty tree
*/
AvlTree( ) : root( NULL )
{
//cout << " [d] AvlTree constructor called. " << endl;
}
/**
* Vector of data initializer (needed for move= operator rvalue)
*/
AvlTree( vector<Comparable> vals ) : root( NULL )
{
insert(vals);
}
//*******************************************************************************************
// START AVL TREES PART II - TODO: Implement
// Other functions to look for include: clone, makeEmpty, printLevelOrder
/**
* Destroy contents of the AvlTree object - Big Five Destructor
*/
~AvlTree( )
{
//cout << " [d] AvlTree Destructor called. " << endl;
// Empty out the AVL Tree and destroy all nodes (makeEmpty?)
}
/**
* Copy other to new object - Big Five Copy Constructor
*/
AvlTree( const AvlTree &other ) : root( NULL )
{
cout << " [d] Copy Constructor Called." << endl;
// Copy contents of other to ourselves (maybe clone?)
// Get a deep copy of other's tree
}
/* ...
Data Structures in C++I am really new to C++, so links are really .pdfrohit219406
Data Structures in C++
I am really new to C++, so links are really hard topic for me. It would be nice if you can provide
explanations of what doubly linked lists are and of some of you steps... Thank you
In this assignment, you will implement a doubly-linked list class, together with some list
operations. To make things easier, you’ll implement a list of int, rather than a template class.
Solution
A variable helps us to identify the data. For ex: int a = 5; Here 5 is identified through variable a.
Now, if we have collection of integers, we need some representation to identify them. We call it
array. For ex: int arr[5]
This array is nothing but a Data Structure.
So, a Data Structure is a way to group the data.
There are many Data Structures available like Arrays, Linked List, Doubly-Linked list, Stack,
Queue, etc.
Doubly-Linked list are the ones where you can traverse from the current node both in left and
right directions.
Why so many different types of Data Structures are required ?
Answer is very simple, grouping of data, storage of data and accessing the data is different.
For example, in case of Arrays we store all the data in contiguous locations.
What if we are not able to store the data in contiguous locations because we have huge data.
Answer is go for Linked List/Doubly-Linked list.
Here we can store the data anywhere and link the data through pointers.
I will try to provide comments for the code you have given. May be this can help you.
#pragma once
/*
dlist.h
Doubly-linked lists of ints
*/
#include
class dlist {
public:
dlist() { }
// Here we are creating a NODE, it has a integer value and two pointers.
// One pointer is to move to next node and other to go back to previous node.
struct node {
int value;
node* next;
node* prev;
};
// To return head pointer, i.e. start of the Doubly-Linked list.
node* head() const { return _head; }
// To return Tail pointer, i.e. end of the Doubly-Linked list.
node* tail() const { return _tail; }
// **** Implement ALL the following methods ****
// Returns the node at a particular index (0 is the head).
node* at(int index){
int cnt = 0;
struct node* tmp = head();
while(tmp!=NULL)
{
if (cnt+1 == index)
return tmp;
tmp = tmp->next;
}
}
// Insert a new value, after an existing one
void insert(node *previous, int value){
// check if the given previous is NULL
if (previous == NULL)
{
printf(\"the given previous node cannot be NULL\");
return;
}
// allocate new node
struct node* new_node =(struct node*) malloc(sizeof(struct node));
// put in the data
new_node->data = new_data;
// Make next of new node as next of previous
new_node->next = previous->next;
// Make the next of previous as new_node
previous->next = new_node;
// Make previous as previous of new_node
new_node->prev = previous;
// Change previous of new_node\'s next node
if (new_node->next != NULL)
new_node->next->prev = new_node;
}
// Delete the given node
void del(node* which){
struct node* head_ref = head();
/* base case */
if(*head_ref == NUL.
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.
How to do the main method for this programBinaryNode.javapublic.pdffeelingcomputors
How to do the main method for this program?
BinaryNode.java
public class BinaryNode
implements Parent{
/** The item associated with this node. */
private E item;
/** The node at the root of the left subtree. */
private BinaryNode left;
/** The node at the root of the right subtree. */
private BinaryNode right;
/** Put item in a leaf node. */
public BinaryNode(E item) {
this.item = item;
// left and right are set to null by default
}
/** no-argument constructor sets everything to null */
public BinaryNode() {
item = null;
left = null;
right = null;
}
/** Put item in a node with the specified subtrees. */
public BinaryNode(E item, BinaryNode left,
BinaryNode right) {
this.item = item;
this.left = left;
this.right = right;
}
/** Put item in a node with the specified subtrees. */
public BinaryNode getChild(int direction) {
if (direction < 0) {
return left;
} else {
return right;
}
}
/** Return the item associated with this node. */
public E getItem() {
return item;
}
/** Return the root of the left subtree. */
public BinaryNode getLeft() {
return left;
}
/** Return the root of the right subtree. */
public BinaryNode getRight() {
return right;
}
/** Return true if this is a leaf. */
public boolean isLeaf() {
return (left == null) && (right == null);
}
/** Replace the item associated with this node. */
public void setItem(E item) {
this.item = item;
}
/** Replace the left subtree with the one rooted at left. */
public void setLeft(BinaryNode left) {
this.left = left;
}
/** Replace the right subtree with the one rooted at right. */
public void setRight(BinaryNode right) {
this.right = right;
}
public void setChild(int direction, BinaryNode child) {
if (direction < 0) {
left = child;
} else {
right = child;
}
}
/**
* Return the String representation of the tree rooted at this node
* traversed preorder.
**/
public String toStringPreorder() {
String result = \"\";
result += item;
if (left != null) {
result += left.toStringPreorder();
}
if (right != null) {
result += right.toStringPreorder();
}
return result;
}
/** Return a String representation of the tree rooted at this node
* traversed inorder.
**/
public String toStringInOrder() {
String result = \"\";
if (left != null) {
result += left.toStringInOrder();
}
result += item;
if (right != null) {
result += right.toStringInOrder();
}
return result;
}
/** Return a String representation of the tree rooted at this node,
* traversed postorder.
**/
public String toStringPostorder() {
String result = \"\";
if (left != null) {
result += left.toStringPostorder();
}
if (right != null) {
result += right.toStringPostorder();
}
result += item;
return result;
}
/**
* Return a String representation of the tree rooted at this node,
* traversed level order.
**/
public String toStringLevelOrder() {
String result = \"\";
Queue> q = new ArrayQueue>();
q.add (this);
while (!(q.isEmpty())) {
BinaryNode node = q.remove ();
result += node.item;
if (node.left != null) {
q.add(node.left);
}
if (node.right != null) {
q.add(node..
The LinkedList1 class implements a Linked list. class.pdfmalavshah9013
/**
The LinkedList1 class implements a Linked list.
*/
class LinkedList1
{
/**
The Node class stores a list element
and a reference to the next node.
*/
private class Node
{
String value;
Node next;
/**
Constructor.
@param val The element to store in the node.
@param n The reference to the successor node.
*/
Node(String val, Node n)
{
value = val;
next = n;
}
/**
Constructor.
@param val The element to store in the node.
*/
Node(String val)
{
// Call the other (sister) constructor.
this(val, null);
}
}
private Node first; // list head
private Node last; // last element in list
/**
Constructor.
*/
public LinkedList1()
{
first = null;
last = null;
}
/**
The isEmpty method checks to see
if the list is empty.
@return true if list is empty,
false otherwise.
*/
public boolean isEmpty()
{
return first == null;
}
/**
The size method returns the length of the list.
@return The number of elements in the list.
*/
public int size()
{
int count = 0;
Node p = first;
while (p != null)
{
// There is an element at p
count ++;
p = p.next;
}
return count;
}
/**
The add method adds an element to
the end of the list.
@param e The value to add to the
end of the list.
*/
public void add(String e)
{
if (isEmpty())
{
first = new Node(e);
last = first;
}
else
{
// Add to end of existing list
last.next = new Node(e);
last = last.next;
}
}
/**
The add method adds an element at a position.
@param e The element to add to the list.
@param index The position at which to add
the element.
@exception IndexOutOfBoundsException When
index is out of bounds.
*/
public void add(int index, String e)
{
if (index < 0 || index > size())
{
String message = String.valueOf(index);
throw new IndexOutOfBoundsException(message);
}
// Index is at least 0
if (index == 0)
{
// New element goes at beginning
first = new Node(e, first);
if (last == null)
last = first;
return;
}
// Set a reference pred to point to the node that
// will be the predecessor of the new node
Node pred = first;
for (int k = 1; k <= index - 1; k++)
{
pred = pred.next;
}
// Splice in a node containing the new element
pred.next = new Node(e, pred.next);
// Is there a new last element ?
if (pred.next.next == null)
last = pred.next;
}
/**
The toString method computes the string
representation of the list.
@return The string form of the list.
*/
public String toString()
{
StringBuilder strBuilder = new StringBuilder();
// Use p to walk down the linked list
Node p = first;
while (p != null)
{
strBuilder.append(p.value + \"\ \");
p = p.next;
}
return strBuilder.toString();
}
/**
The remove method removes the element at an index.
@param index The index of the element to remove.
@return The element removed.
@exception IndexOutOfBoundsException When index is
out of bounds.
*/
public String remove(int index)
{
if (index < 0 || index >= size())
{
String message = String.valueOf(index);
throw new IndexOutOfBoundsException(message);
}
String element; // The element to return
if (index == 0)
{
// Removal of first item in the list
element.
Describe an algorithm for concatenating two singly linked lists L and.pdfdeepak596396
Dataset:
https://docs.google.com/spreadsheets/d/1NxuGt4LJ3ofi2PaWLWpAl90JmfqMKcGV/edit?usp=sharing&ouid=111109979069524025260&rtpof=true&sd=true
Q1) What is the average tenure of those customers of the telecom operator who are still with the
company as a customer and also those who have stopped using the services provided by the
company? (1 mark)
Here, churn = 'No' means that the customer is currently associated with the company, and churn
= 'Yes' means that the customer has stopped using the services provided by the company.
Q2)What is the monthly average revenue generated by the customers who are with the company
and also those who have left? (1 mark)
Q3) Find the percentage of churn and non-churn customers for each category of the following
services: (4 marks)
-MultipleLines
-PaperlessBilling
-OnlineSecurity
-OnlineBackup
-DeviceProtection
-TechSupport
-StreamingTV
-StreamingMovies.
Problem I. As shown in the pedigree below, a pair of first cousins (.pdfsivakumar19831
Problem I. As shown in the pedigree below, a pair of first cousins (I and K) marry an unrelated
pair of first cousins (J and L). Their children M and N produce child O.
Q1. Calculate the inbreeding coefficient (f) of O (express answers to Q1 and Q3 to three decimal
places). Assume that f= 0 for all ancestors. (Hint: To help you out, I have shaded individuals
who cannot contribute to autozygosity.) To show your work, use the letter names to indicate each
path/loop that contributes to autozygosity. For example: path 1 = M-I-E…
Q2. Interpret your result. What does this value of f indicate?
Q3. Recalculate f for child O when f=1/2 for great-great grandmother D (f=0 for all other
ancestors). Hint: After you have calculated all the loops above, you’ll adjust just the loop that
includes ancester D to account for her ancestral inbreeding using the formula presented in class
(and text). B 0271 M H K E
Solution
Path 1:
· O-M-I-E-A-F-K-N-O
· O-M-I-E-B-F-K-N-O
So, the probability that a copy of gene in A makes the way down to O via E and a copy of gene
in B makes the way down to O via F =(½)n = (½)7=0.00781. Here n= node=7
Path 2:
· O-N-L-H-D-G-J-M-O
· O-N-L-H-C-G-J-M-O
Similarly, like the first one the total probability in path 2 will be same that is 0.00781.
Thus inbreeding co-efficient = 0.00781+0.00781=0.01562.
2. Generally, the higher the level of inbreeding closer the coefficient of relationship approaches a
value of 1 and approaches a value of 0 for individuals with remote common ancestors.
As here the value of inbreeding co-efficient is approximately 0 so we can conclude that
1. the common ancestors are not inbred.
2. O has remote common ancestors means they are distantly related.
3. When a common ancestor is itself inbred the inbreeding coefficient is = (1/2)n (1+ inbreeding
co-efficient of common ancestor) ,
The probability that a copy of gene in D makes the way to O = (1/2)7 = 0.00781
Therefore, inbreeding co-efficient is = 0.00781 * (1 + 1/2) =0.01172.
Points are assigned both on the correctness of the answer and the com.pdfsivakumar19831
Points are assigned both on the correctness of the answer and the completeness of the problem -
show all givens, state all assumptions, show all calculations. 1. Transportation affects society in
many ways and is frequently in the news. Find a transportation news article for a local, regional,
or national source (newspaper, credible internet site, etc.). Provide a link to the article and
summarize the article and explain the importance.
Solution
Hello,
As stated I am providing you with a link to the *.Pdf file regarding Transportation and its role in
society.
https://nptel.ac.in/courses/105101087/downloads/Lec-3.pdf
This is a very credible source.
Transportation is a non separable part of any society. It exhibits a very close relation to the style
of life, the range and location of activities and the goods and services which will be available for
consumption. Advances in transportation has made possible changes in the way of living and the
way in which societies are organized and therefore have a great inuence in the development of
civilizations. This chapter conveys an understanding of the importance of transportation in the
modern society by presenting selected characteristics of existing transportation systems, their use
and relationships to other human activities. Transportation is responsible for the development of
civilizations from very old times by meeting travel requirement of people and transport
requirement of goods. Such movement has changed the way people live and travel. In developed
and developing nations, a large fraction of people travel daily for work,shopping and social
reasons. But transport also consumes a lot of resources like time,fuel, materials and land..
Predefined Characters in C Type. Please make sure the program compil.pdfsivakumar19831
Predefined Characters in C Type. Please make sure the program compiles thanks :) // This
program reads one character from the keyboard and will // - convert it to uppercase, if it is
lowercase // - convert it to lowercase, if it is uppercase // - display a message, if it is not a letter
of the alphabet #include #include using namespace std; int main() char c coutc if (isalpha(c))
//check to see if it is a letter of alphabet if (isupper(c))//check to see if it is uppercase cout
Solution
#include
#include
using namespace std;
int main()
{
char c;
cin.get(c); //cin.get() input the character which can be of any type
if(isalpha(c))
{
if(isupper(c))
{
cout<<\"Your character \"<.
On January 1, 2017, Pinnacle Corporation exchanged $3,527,500 cash f.pdfsivakumar19831
On January 1, 2017, Pinnacle Corporation exchanged $3,527,500 cash for 100 percent of the
outstanding voting stock of Strata Corporation. On the acquisition date, Strata had the following
balance sheet:
Cash
$
284,000
Accounts payable
$
383,000
Accounts receivable
311,000
Long-term debt
3,060,000
Inventory
443,000
Common stock
1,500,000
Buildings (net)
1,920,000
Retained earnings
1,205,000
Licensing agreements
3,190,000
$
6,148,000
$
6,148,000
Pinnacle prepared the following fair-value allocation:
Fair value of Strata (consideration transferred)
$
3,527,500
Carrying amount acquired
2,705,000
Excess fair value
$
822,500
to buildings (undervalued)
$
480,000
to licensing agreements (overvalued)
(110,000
)
370,000
to goodwill (indefinite life)
$
452,500
At the acquisition date, Strata’s buildings had a 10-year remaining life and its licensing
agreements were due to expire in 5 years. At December 31, 2018, Strata’s accounts payable
included an $86,600 current liability owed to Pinnacle. Strata Corporation continues its separate
legal existence as a wholly owned subsidiary of Pinnacle with independent accounting records.
Pinnacle employs the initial value method in its internal accounting for its investment in Strata.
The separate financial statements for the two companies for the year ending December 31, 2018,
follow. Credit balances are indicated by parentheses.
Pinnacle
Strata
Sales
$
(7,683,000
)
$
(3,328,000
)
Cost of goods sold
4,940,000
1,835,000
Interest expense
338,000
207,000
Depreciation expense
630,000
448,000
Amortization expense
638,000
Dividend income
(35,000
)
Net income
$
(1,810,000
)
$
(200,000
)
Retained earnings 1/1/18
$
(5,160,000
)
$
(1,560,000
)
Net income
(1,810,000
)
(200,000
)
Dividends declared
600,000
35,000
Retained Earnings 12/31/18
$
(6,370,000
)
$
(1,725,000
)
Cash
$
282,000
$
547,000
Accounts receivable
1,255,000
305,000
Inventory
1,295,000
1,565,000
Investment in Strata
3,527,500
Buildings (net)
6,060,000
2,084,000
Licensing agreements
1,914,000
Goodwill
408,000
Total assets
$
12,827,500
$
6,415,000
Accounts payable
$
(337,500
)
$
(950,000
)
Long-term debt
(3,120,000
)
(2,240,000
)
Common stock
(3,000,000
)
(1,500,000
)
Retained earnings 12/31/18
(6,370,000
)
(1,725,000
)
Total Liabilities and OE
$
(12,827,500
)
$
(6,415,000
)
a. Prepare a worksheet to consolidate the financial information for these two companies.
PINNACLE COMPANY AND SUBSIDIARY STRATA
Consolidation Worksheet
For Year December 31, 2018
Consolidation Entries
Accounts
Pinnacle
Strata
Debit
Credit
Consolidated Totals
Sales
$(7,683,000)
$(3,328,000)
Cost of goods sold
4,940,000
1,835,000
Interest expense
338,000
207,000
Depreciation expense
630,000
448,000
Amortization expense
638,000
Dividend income
(35,000)
Net income
$(1,810,000)
$(200,000)
$0
Retained earnings 1/1/18
(5,160,000)
(1,560,000)
Net income
(1,810,000)
(200,000)
0
Dividends declared
600,000
35,000
Retained earnings 12/31/18
$(6,370,000)
$(1,725,000)
$0
Cash
$282,000
$547,000
Accounts rec.
Most of the functions of a cell membrane are performed by proteins ch.pdfsivakumar19831
Most of the functions of a cell membrane are performed by proteins cholesterol None of this
glycolysis Select all of the groups of membrane proteins All of the statements are correct
Solution
13) It is a transmembrane protein
14) Transmembrane protein pass through both sides of the lipid bilayer and protude from both
extracellular and cytoplasmic side of the membrane. It acts as a gateway to permit transport of
proteins across membrane.
17) Transmembrane proteins are amphipathic as they are present in the bilayer and also protrude
out of the membrane
12) Membrane proteins can be peripheral, intergral and lipid anchored..
Objectives 1. Understand the design, implementation, usage and limita.pdfsivakumar19831
Objectives 1. Understand the design, implementation, usage and limitation of a Linked List
ADT 2. Gain experience implementing abstract data t types using already developed data
structures Recognize and practice possible linked list applications. 3. Overview In this project,
you should write a simple line editor. Keep the entire text on a linked list, one line in a separate
node. Start the program with entering EDIT file, after which a prompt appears along with the line
number. If the letter I is entered with a number n following it, then insert the text to be followed
before line n. If I is not followed by a number, then insert the text before the current line. If D is
entered with two numbers n and m, one n, or no number following it, then delete lines n through
m, line n, or the current line. Do the same with the command L, which stands for listing lines. If
A is entered, then append the text to the existing lines. Entry E signifies exit and saving the text
in a file. Here is an Example: EDIT testfile 1> The first line 2> 3> And another line 4>I 3 3 The
second line 4> One more line 5> L 1> The first line 3 The second line 4> One more line 5 And
another line 5> D 2 4> L // This is now line 5, not 3; // line 5, since L was issued from line 5
//line 4, since one line was deleted; 1 The first line 2> The second line 3> One more line 4> And
another line 4> E // this and the following lines // now have new numbers
Solution.
New Nirvana Ltd is a company controlled by the members of the hard r.pdfsivakumar19831
New Nirvana Ltd is a company controlled by the members of the hard rock band, N/N. A
number of wholly owned subsidiaries of New Nirvana Ltd are involved in setting up and running
the band’s concerts. One of the subsidiary companies, Nuclear Blast Sounds Pty Ltd, is
responsible for setting up the sound equipment at N/N concerts in Australia. At a recent N/N
concert in Sydney, Nuclear Blast Sounds Pty Ltd negligently set the sound levels too 2 high with
the result that five audience members suffered permanent hearing loss. Unfortunately for those
audience members, Nuclear Blast Sounds Pty Ltd had no negligence insurance and cannot pay
the likely damages claims. Advise the injured audience members whether they can make New
Nirvana Ltd liable for Nuclear Blast Sounds Pty Ltd’s negligence.
Solution
Facts of the Case: Nuclear Blast Sounds Pty Ltd which is a wholly owned subsidiary of New
Nirvana Ltd negligently set the sound levels too high with the result that five audience members
suffered permanent hearing loss.
Case Law Reference:The Case of Chandler vs Cape plc has established that a parent enterprise
may be held liable for breaches of health and safety laws by a subsidiary Enterprise.
Explanation: In the given case, Nuclear Blast Sounds Pty Ltd is a wholly owned subsidiary of
New Nirvana Ltd.It naturally acts on the directions of holding company. Since the permanent
hearing loss caused to the audience is due to ngligence of Nuclear Blast Sounds Pty Ltd the
audience has full rights to sue New Nirvana Ltd if in case the subsidiary is unable to honour their
claims.
New Nirvana Ltd has no right to use Corporate Veil in this case as the subsidiary is a wholly
owned subsidiary and it acts on direction of New Nirvana Ltd.
Conclusion: Injured audience members can make New Nirvana Ltd liable for Nuclear Blast
Sounds Pty Ltd’s negligence..
Malaria being spread by mosquitoes is an example of which type of dis.pdfsivakumar19831
Malaria being spread by mosquitoes is an example of which type of disase
transmission? Vehicle-borne Zeonosis Fontice-borne Vector-borne The disease-
evoking power of a pathogen is called which of the following?
Invasiveness Variability Virulence Communicability
The likelihood of a pathogen or agent being trans-from one infected person to another susceptive
person is referred to as which of the following?
Invasiveness Variability Virulence Communicability
Metabolic diseases are best defined by which of the
following? A collective name that refers to a group
of many diseases with one common characteristic-
uncontrolled growth of mutated cells A lower level of mental, physical,
or moral state than is normal Diseases existing at birth and often before birth, or
that develop during the first month of life Caused by
the body reacting to an invasion of or injury by a
foreign object or substance Any of the diseases or
disorders that disrupt the process of converting food
to energy on a cellular level; affects the ability of the
cell to perform critical biochemical reactions that
involve the processing or transport of proteins (amino acids),
carbohydrates (sugars and starches), or lipids (fatty acids) As a general rule,
a disease is included on a state\'s list of notifiable diseases under what
conditions? Causes serious morbidity or death Has
the potential to spread Can be controlled with
appropriate intervention All of the above conditions
warrant reporting the disease. The natural course of
communicable disease involves a susceptible host; a
point of exposure; a cube clinical disease phase; the
clinical disease phase; and a phase of recovery, disability, or death. Which phase is related to the
latency period? Susceptibility phase Subclinical phase Clinical disease phase Recovery,
disability, or death phase Which term refers to quarantine-type activities
that are conducted on an inpatient basis in a hospital
or nursing home? Quarantine Isolation Good
hygiene Immunization Chemoprophylaxis What herd
immunity threshold did Jonas Salk suggest would
make it infeasible for there to be a polio epidemic? 55% 65% 75% 85%
Solution
13. b)- zoonosis
14. c)-virulence
15. d)- communicability
16. e)
17. d) - all of the above conditions
18. b) - subclinical phase
19. b) - isolation
20. d) - 85%.
In oxidative phosphorylation and phosphorylation, the enzyme ATP synt.pdfsivakumar19831
In oxidative phosphorylation and phosphorylation, the enzyme ATP syntheses couples the
synthesis of ATP to which one of the following processes? A. The facilitated diffusion of
protons B. The splitting of water with the release of O_2 C. The excilation of the Chlorophyll
reaction center D. The reduction of NADP\' through NADP* reductase E. carboxylation of
RuBP using the enzyme rubisco During which process(es) does the splitting of carbon dioxide
to form oxygen gas and carbon A. photosynthesis B. both photosynthesis and respiration C.
respiration D. neither photosynthesis nor respiration E. photorespiration. Which of the
following describes a property of water necessary for life? A. Water changes temperature
rapidly. B. Water is non-cohesive. C. Water is most dense as a solid. D. Water has constant
high pH. E. Water can dissolve many chemicals. What is the lowest level of biological
organization that can perform all of the activities required for life? A. organelle B. molecule C.
cell D. tissue E. organism
Solution
30. The proton gradient generated during electron transport drives the synthesis of ATP through
ATP synthase. This process is similar in both oxidative phosphorylation and
photophosphorylation.
Excitation of the chlorophyll reaction center, the splitting of water with the release of O2 and, the
reduction of NADP+ through NADP+ reductase occur only during the process of
photophosphorylation.
Carboxylation of RuBP using the enzyme rubisco takes place during Calvin cycle.
Therefore, option A is correct.
The enzyme ATP synthase couples the synthesis of ATP to the facilitated diffusion of protons
during oxidative phosphorylation, and photophosphorylation.
31. Photosynthesis is the process in which light energy is used to reduce carbon dioxide to yield
carbohydrates.
During respiration, oxygen is consumed and carbon dioxide is released.
Therefore, option A is correct.
The splitting of carbon dioxide to form oxygen gas and yield carbohydrates occurs during the
process of photosynthesis.
32. Water helps to regulate the temperature of the body.
Water does not have high ph. It has a neutral ph.
Water can dissolve many chemicals. It helps to transport essential molecules and chemicals
throughout the body.
Therefore, option E is correct.
33. Cell is the lowest level of biological organization that can perform all of the activities
required for life.
Cells that perform the same function are grouped together to form tissues,
An aggregation of different tissues for a specialized function is called as an organ.
Therefore, option C is correct.
Cell is the lowest level of biological organization that can perform all of the activities required
for life..
List and define the significance of the following proteinsstructures.pdfsivakumar19831
List and define the significance of the following proteins/structures involved in DNA
replication: DNA polymerase III, DNA polymerase I, Primase, Single stranded binding proteins
(SSBPs), Helicase, Ligase, Primers, Topoisomerase, Anti-parallel ds DNA, Leading strand of
DNA, Lagging Strand of DNA, replication bubble, and deoxyribonucleotide tri-phosphates
(dNTPs). Describe the process of DNA replication using all of the terms that were listed (and
defined) above. Make sure you include the difference in how the leading strand and lagging
strand are synthesized. Also, include any differences (covered in class) between bacterial DNA
replication and eukaryotic DNA replication. Lastly, include a hand drawn diagram with each of
these structures and enzymes in different colors to illustrate how this process occurs.
Solution
DNA Replication: it is the biological process in which two identical replicas of DNA are
produced. It involves many steps and components.
Protein/ structures involved in DNA replication are as follows:
DNA polymerase III: it was discovered by Thomas Kornberg and Malcolm Gefter. It is an
enzyme which has its role to play in prokaryotic DNA replication. It has high processivity which
is the number of nucleotides added per binding event. It can also perform proof reading which is
the correction of wrongly added nucleotides is
DNA polymerase I: it was first discovered polymerase enzyme and Arthur Korenberg discovered
it. It does not have a role in replication but poses exonuclease activity that is removal of
nucleotides during DNA repair.
Primase: it is a type of RNA polymerase. This is very important in initiation of DNA replication
because no polymerase can synthesise a DNA without small single stranded RNA. Thus a
primase help in synthesising such small single stranded RNA complementary to the template
DNA. After initiation, this RNA piece is removed.
Single-stranded binding proteins (SSBPs): these are the class of proteins that prevent premature
binding of nucleotides to template DNA. They protect single stranded DNA from being digested
by nucleases and also prevents looping of single stranded DNA, so that other enzymes can
perform their function.
Helicases: these are the group of enzymes which help in separating two strands of DNA for the
process of replication.
Ligases: another class of enzymes which help in binding of two strands of DNA by catalysing
formation of phosphodiester bond between the two strands.
Primer: a short single stranded DNA/RNA that serves as a starting point for the DNA synthesis.
Primase helps in the formation of primer.
Topoisomerases: during replication DNA over wounds ahead the replication point making
further replication difficult, in such instance topoisomerase help in unwinding supercoiled DNA.
Anti-parallel double strand: DNA is made of two strands running in opposite directions and
hence anti parallel one runs from 5’ to 3’ and the other from 3’ to 5’.
Leading strand: DNA replication on leading stra.
In this TEM image, what does the TEM allow you to view that would no.pdfsivakumar19831
In this TEM image, what does the TEM allow you to view that would not be visible using the
Compound Microscope?
The human cell
SELECT ALL ANSWERS THAT APPLYThe structure of internal cell organellesThe Human
Immunodeficiency Virus
The human cell
SELECT ALL ANSWERS THAT APPLY
Solution
Answers are
The structure of internal cell organelles
And
The human immuno deficiency virus.
Transmission electron microscope TEM can be used to see extremely small things like cell
organelles and viruses. With compound Microscope we cannot see those. Human cell can be
seen with compound Microscope..
The Art Pastor's Guide to Sabbath | Steve ThomasonSteve Thomason
What is the purpose of the Sabbath Law in the Torah. It is interesting to compare how the context of the law shifts from Exodus to Deuteronomy. Who gets to rest, and why?
Model Attribute Check Company Auto PropertyCeline George
In Odoo, the multi-company feature allows you to manage multiple companies within a single Odoo database instance. Each company can have its own configurations while still sharing common resources such as products, customers, and suppliers.
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.
The Indian economy is classified into different sectors to simplify the analysis and understanding of economic activities. For Class 10, it's essential to grasp the sectors of the Indian economy, understand their characteristics, and recognize their importance. This guide will provide detailed notes on the Sectors of the Indian Economy Class 10, using specific long-tail keywords to enhance comprehension.
For more information, visit-www.vavaclasses.com
How to Split Bills in the Odoo 17 POS ModuleCeline George
Bills have a main role in point of sale procedure. It will help to track sales, handling payments and giving receipts to customers. Bill splitting also has an important role in POS. For example, If some friends come together for dinner and if they want to divide the bill then it is possible by POS bill splitting. This slide will show how to split bills in odoo 17 POS.
Ethnobotany and Ethnopharmacology:
Ethnobotany in herbal drug evaluation,
Impact of Ethnobotany in traditional medicine,
New development in herbals,
Bio-prospecting tools for drug discovery,
Role of Ethnopharmacology in drug evaluation,
Reverse Pharmacology.
The French Revolution, which began in 1789, was a period of radical social and political upheaval in France. It marked the decline of absolute monarchies, the rise of secular and democratic republics, and the eventual rise of Napoleon Bonaparte. This revolutionary period is crucial in understanding the transition from feudalism to modernity in Europe.
For more information, visit-www.vavaclasses.com
Operation “Blue Star” is the only event in the history of Independent India where the state went into war with its own people. Even after about 40 years it is not clear if it was culmination of states anger over people of the region, a political game of power or start of dictatorial chapter in the democratic setup.
The people of Punjab felt alienated from main stream due to denial of their just demands during a long democratic struggle since independence. As it happen all over the word, it led to militant struggle with great loss of lives of military, police and civilian personnel. Killing of Indira Gandhi and massacre of innocent Sikhs in Delhi and other India cities was also associated with this movement.
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxEduSkills OECD
Andreas Schleicher presents at the OECD webinar ‘Digital devices in schools: detrimental distraction or secret to success?’ on 27 May 2024. The presentation was based on findings from PISA 2022 results and the webinar helped launch the PISA in Focus ‘Managing screen time: How to protect and equip students against distraction’ https://www.oecd-ilibrary.org/education/managing-screen-time_7c225af4-en and the OECD Education Policy Perspective ‘Students, digital devices and success’ can be found here - https://oe.cd/il/5yV
Objective Binary Search Tree traversal (2 points)Use traversal.pp.pdf
1. 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()
{
2. 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);
}
3. /** @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()));
}
}
return rt;
}
private BSTNode getmin(BSTNode rt) {
if (rt.left() == null) return rt;
return getmin(rt.left());
}
4. private BSTNode deletemin(BSTNode rt) {
if (rt.left() == null) return rt.right();
rt.setLeft(deletemin(rt.left()));
return rt;
}
private void printhelp(BSTNode rt) {
if (rt == null) return;
printhelp(rt.left());
printVisit(rt.element());
printhelp(rt.right());
}
private StringBuffer out;
public String toString() {
out = new StringBuffer(400);
printhelp(root);
return out.toString();
}
private void printVisit(E it) {
out.append(it + " ");
}
}
class BSTNode implements BinNode {
private Key key; // Key for this node
private E element; // Element for this node
private BSTNode left; // Pointer to left child
private BSTNode right; // Pointer to right child
/** Constructors */
public BSTNode() {left = right = null; }
public BSTNode(Key k, E val)
{ left = right = null; key = k; element = val; }
public BSTNode(Key k, E val,
BSTNode l, BSTNode r)
{ left = l; right = r; key = k; element = val; }
/** Get and set the key value */
public Key key() { return key; }
public void setKey(Key k) { key = k; }
5. /** Get and set the element value */
public E element() { return element; }
public void setElement(E v) { element = v; }
/** Get and set the left child */
public BSTNode left() { return left; }
public void setLeft(BSTNode p) { left = p; }
/** Get and set the right child */
public BSTNode right() { return right; }
public void setRight(BSTNode p) { right = p; }
/** @return True if a leaf node, false otherwise */
public boolean isLeaf()
{ return (left == null) && (right == null); }
}
public interface Dictionary {
/** Reinitialize dictionary */
public void clear();
/** Insert a record
@param k The key for the record being inserted.
@param e The record being inserted. */
public void insert(Key k, E e);
/** Remove and return a record.
@param k The key of the record to be removed.
@return A maching record. If multiple records match
"k", remove an arbitrary one. Return null if no record
with key "k" exists. */
public E remove(Key k);
/** Remove and return an arbitrary record from dictionary.
@return the record removed, or null if none exists. */
public E removeAny();
/** @return A record matching "k" (null if none exists).
If multiple records match, return an arbitrary one.
@param k The key of the record to find */
public E find(Key k);
/** @return The number of records in the dictionary. */
public int size();
};
7. // parametrized constructor
public BST(BSTNode root) {
this.root = root;
}
// arranging nodes when cases like deleting node
public BSTNode MinAttach(BSTNode right, BSTNode left) {
if(right.getLeft() == null) {
right.setLeft(left);
return right;
}
else {
right.setLeft(MinAttach(right.getLeft(), left));
return right;
}
}
// deleting entry ..passing key
public void delete(K key) {
this.root = deleteNodeRecursively(root, key);
}
// deleting nodes
public BSTNode DeleteDoubNode(BSTNode node) {
if(node.getLeft() == null) {
//at the bottom of the nodes.
return node.getRight();
}
else {
//set the left node as the right of the one we found at the bottom.
node.setLeft(DeleteDoubNode(node.getLeft()));
}
return node;
}
// recursively deleting node
public BSTNode deleteNodeRecursively(BSTNode node, K key) {
// check right node to delete
if(key.compareTo(node.getKey()) == 0) {
// check for leaf
8. if((node.getLeft() == null) && (node.getRight() == null)) {
return null;
}
//check node with right child
else if((node.getLeft() == null) && (node.getRight() != null)) {
return node.getRight();
}
//check node with left child
else if((node.getLeft() != null) && (node.getRight() == null)) {
return node.getLeft();
}
// check node with two children
else if((node.getLeft() != null) && (node.getRight() != null)) {
BSTNode replacementNode = findMin(node.getRight());
BSTNode backupLeft = node.getLeft();
replacementNode.setRight(DeleteDoubNode(node.getRight()));
replacementNode.setLeft(backupLeft);
return replacementNode;
}
else {
return node;
}
}
//check key is less than
else if(key.compareTo(node.getKey()) < 0) {
if(node.getLeft() != null) {
node.left = deleteNodeRecursively(node.getLeft(), key);
return node;
}
}
//check key is greater than
else {
if(node.getRight() != null) {
node.right = deleteNodeRecursively(node.getRight(), key);
return node;
}
9. }
return node;
}
// returns depth of tree
public int depth() {
return depthPostOrder(root, 0);
}
// find minimum value of BST
public BSTNode findMin(BSTNode node) {
while(node.getLeft() != null) {
node = node.getLeft();
}
return node;
}
// BST inorder
public void inorder(BSTNode node) {
if(node != null) {
inorder(node.getLeft()); //get first left keys
System.out.println("key: " + node.getKey().toString() + " element: " +
node.getElement().toString());
inorder(node.getRight());
}
}
// inserting new element
public void insert(K key, E element) {
if(root == null) {
root = new BSTNode(key, element, null, null);
}
else {
insertBelow(root, key, element);
}
}
// recursive preorder depth
int depthPostOrder(BSTNode node, int current_depth) {
if(node != null) {return Math.max(depthPostOrder(node.getLeft(), current_depth+1),
10. depthPostOrder(node.getRight(), current_depth+1));
}
else return current_depth;
}
// printing whole tree
public void printTree() {
//printing recursively
System.out.println(" Outputting BSTree...");
inorder(root);
}
// serach method
public E search(K key) {
BSTNode nodeFound;
nodeFound = searchingNode(key);
if(nodeFound == null) {
return null; //not found
}
else return searchingNode(key).getElement(); //call another helper method.
}
// searching node
public BSTNode searchingNode(K key) {
if(key == null) {
return null;
}
if(root == null) {
return null; //if empty tree
}
//if both keys are equal
if(key.compareTo(root.getKey()) == 0) {
return root;
}
//less than root key
else if(key.compareTo(root.getKey()) < 0) {
return searchBelow(root.getLeft(), key); //call the recursive search method.
}