Question

must be coded in c++ without any STL libraries sadly :( so im struggling on this...

must be coded in c++ without any STL libraries sadly :( so im struggling on this problem, any help would be greatly appreciated, thanks in advance! :) assignment is due tomorrow and im really struggling on this last question :(

a. Begin by implementing a BST for integers. The underlying structure is a linked list. You
need these methods:
i. BST(); -- Constructor
ii. void put (int) – Inserts a value into the BST.
iii. Void put(int[] a) – Inserts an entire array ‘a’ into the BST.
iv. int search(int key) – Searches for a value in the BST. If found, return the key. If
not found, return 0 and print ‘Value not found!’ to the console. Additionally, print out the total number of comparisons needed (whether the key is found or
not).
v. int returnSize(); -- returns the total number of nodes in the BST.
See Slides 3-10 on Binary Search Trees to see how a BST might be structured with these
methods. The implementation is effectively the same as shown.
b. Now, we will attempt to balance the tree after the values have been inserted.
Implement these methods:
i. int[] a sortedTree(); -- Outputs the tree in sorted order of an array.
ii. BST balanceTreeOne(); -- Balances the tree by creating a new BST and inserting
the values of the sorted array in a way such that the tree height is balanced.
Linear insertion of the sorted values would be the worst possible height.
c. During Red-Black Trees, we discussed the concept of ‘rotations’. Rotations of a node
involve pushing a node to the left or right and reconnecting the parent/children nodes.
Please see Slides 26-29 of the Balanced Search Tree lectures to see what occurs in
rotations. Implement these methods for your BST:
i. Node rotateRight(Node h) – Rotates a given node h to the right and returns the
new parent node after rotation. See the Slides for detail.
1. Note! You need to update the code here to cancel the function if there
are no left subchildren!
ii. Node rotateLeft(Node h) – Rotates a given node h to the left and returns the
new parent node after rotation. See the slides for detail.
1. Note! You need to update the code here to cancel the function is there
are no right subchildren!
iii. void transformToList(); -- Performs a series of right rotations on the BST until
the BST is just a linked list oriented to the right. The logic is like so:
1. Begin at the root, and check if there are left subchildren. If there are,
rotate the root to the right.
2. If the root *still* has left children after rotating, continue rotating right
until there are no more left children at the root.
3. Move to the right. Check if this parent node has left children. If so,
rotateRight on the parent. Continue doing so until there are no more
left children.
4. Repeat all the way down until there are no more nodes that have left
children. The tree is now a right-leaning linked list.
d. We will now attempt to balance the BST without creating new memory, as we did in
Part b. Implement these methods:
i. void balanceTreeTwo(); -- Restructures the BST. It will do this by following this
logic:
1. First, restructure the tree by calling transformToList(); to turn it into a
right-leaning linked list.
2. Compute the parameter ? = (? + 1) − 2
⌊log2 ?⌋
.
a. N is the total number of nodes, ⌊log2 ?⌋ means to compute the
floor of log2 ?.
3. From the root of the tree (which is now a right-leaning linked list),
perform left rotations on every odd node until ? odd nodes have been
rotated.
a. Example: Imagine a list 0->1->2->3->4. If ? = 2, then we
perform rotateLeft() on the ‘0’ node and the ‘2’ node. That’s
exactly ? odd nodes.
4. Compute the parameter ? = ⌊log2 ?⌋ − 1.
5. For K times, compute left rotations on the remaining right-leaning odd
nodes.
a. In the example list above, we did left rotations on 2 odd nodes.
If we ignore the new left links and just look at the right links, we
have 1->3->4. We would do left rotations on 1 and 4.
6. Congratulations, the tree is now balanced!
e. Include a PDF, Problem2.PDF. Include these parts:
i. How does the algorithm of balanceTreeTwo(); balance the tree -- why does this
work? Explain it for all steps.
ii. What is the total time complexity of the balanceTreeOne(); function in the
average case? Consider how this function worked. balanceTreeOne(); first calls
sortedTree(); then creates a new BST out of that. The cost of this should be
?(??????????????) = ?(??????????) + ?(???(???[?])). You will fill this in
for the actual values.
iii. What is the space complexity of the balanceTreeOne(); function?
iv. What is the total time complexity of the balanceTreeTwo(); function? Perform a
similar analysis to I, where you sum up the cost of the internal operations.
v. What is the space complexity of balanceTreeTwo();?

0 0
Add a comment Improve this question Transcribed image text
Answer #1

bst.cpp

#include<iostream>

using namespace std;

//binary tree structure

struct Node

{

int data;

struct Node *left,*right;

};

class BST

{

public :

Node *root;

BST() //constructor (i)

{

root=NULL;

}

//Create a node

Node *newNode(int num)

{

Node *newnode=new Node;

newnode->data=num;

newnode->left=newnode->right=NULL;

return newnode;

}

//Recursive method to insert in BST

Node * insert(Node *root,int data) //insert in Binary search Tree

{

Node *newnode=newNode(data);

if(root==NULL)

{

root=newnode;

return root;

}

if(root->data>data)

root->left=insert(root->left,data); //insert in left if data is less than root data **change this line in your algorithm

else

root->right=insert(root->right,data); //insert in right if data is greater than root data ** change this line your algorithm

  

return root;  

}

//insert a num in BST (ii)

void put(int num)

{

root=insert(root,num);

}

//insert array in BST (iii)

void put(int a[])

{

while(*(a+1))

{

root=insert(root,*a);

a++;

}

}

//inorder recursive method

void inorderRec(Node *root)

{

if(root)

{

inorderRec(root->left);

cout<<root->data<<" ";

inorderRec(root->right);

}

}

//recursive method to search num in BST

int searchRec(Node *root,int num)

{

if(root==NULL)

return 0;

if(root->data==num)

return root->data;

if(root->data>num)

return searchRec(root->left,num);

  

return searchRec(root->right,num);

}

//recursive function to find size of tree

int nodeCount(Node *root)

{

if(root==NULL)

return 0;

return 1+nodeCount(root->left)+nodeCount(root->right);  

}

int returnSize() //return size (v)

{

return nodeCount(root); //return recursively

}

int search(int key) //search key (iv)

{

return (searchRec(root,key)); //search number recursively

}

void inorder()

{

inorderRec(root); //print inorder recursively

}

};// end of class BST

int main()

{

BST ob;

ob.put(15); //insert in binary search tree

int a[]={9,30,51,23,11,5,7,10};

ob.put(a);//insert array in binary search tree

cout<<" Binary Search tree inorder : ";

ob.inorder(); //print inorder to check data in tree

if(ob.search(23)) //search function

cout<<"\n 23 found in Binary Search Tree";

else

cout<<"\n Not found Binary Search Tree";

if(ob.search(90))

cout<<"\n 23 found in Binary Search Tree";

else

cout<<"\n 90 Not found Binary Search Tree";   

cout<<"\n Number of nodes in Binary Search Tree : "<<ob.returnSize(); //return size of Binary search Tree

return 0;

}

OUTPUT

Binary Search tree inorder : 5 7 9 10 11 15 23 30 51
23 found in Binary Search Tree
90 Not found Binary Search Tree
Number of nodes in Binary Search Tree : 9

Add a comment
Know the answer?
Add Answer to:
must be coded in c++ without any STL libraries sadly :( so im struggling on this...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • C++: PLEASE HELP~!!! ~~~~~~~~ Implement bool AVLTree::deleteNode(string ss) method. Function deleteNode() tries to delete the node...

    C++: PLEASE HELP~!!! ~~~~~~~~ Implement bool AVLTree::deleteNode(string ss) method. Function deleteNode() tries to delete the node containing value ss. If there is no such node, it returns false. Otherwise, it deletes the node, check the balance of the tree, rebalance the tree if it is necessary. When you delete a node, consider three different scenarios: -The node is a leaf -The node has only ONE child subtree -The node has two child subtrees Important: When you implement this project, do...

  • Does not pass the testcase testDTreeAdvancedReRootchangesParent Java I'm trying to extend the implementation of a general...

    Does not pass the testcase testDTreeAdvancedReRootchangesParent Java I'm trying to extend the implementation of a general tree with new operations that change the structure of the tree. I've created 5 classes: Node.java, SimpleNode.java, Tree.java, RerootableTree.java and SimpleTree.java(which is the main java class that I need to change). The code does not pass ONE TESTCASE : testDTreeAdvancedReRootchangesParent The code passes all the other testcases except theone mentioned above. This is because in the SimpleTree.java the method "reRoot(Node newRoot)" is most likely...

  • C++ EXERCISE (DATA STRUCTURES). I just need a code for some functions that are missing. Please...

    C++ EXERCISE (DATA STRUCTURES). I just need a code for some functions that are missing. Please help me figure out. Thanks. C++ BST implementation (using a struct) Enter the code below, and then compile and run the program. After the program runs successfully, add the following functions: postorder() This function is similar to the inorder() and preorder() functions, but demonstrates postorder tree traversal. displayParentsWithTwo() This function is similar to the displayParents WithOne() function, but displays nodes having only two children....

  • Using the following implementation of Tree class Node   {   public int iData;              // data item (key)   public...

    Using the following implementation of Tree class Node   {   public int iData;              // data item (key)   public double dData;           // data item   public Node leftChild;         // this node's left child   public Node rightChild;        // this node's right child   public void displayNode()      // display ourself      {      System.out.print('{');      System.out.print(iData);      System.out.print(", ");      System.out.print(dData);      System.out.print("} ");      }   }  // end class Node //------------------------------------------------------------------ import java.io.IOException; import java.util.Stack; public class Tree { private Node root; // first node of tree // ------------------------------------------------------------- public Tree() // constructor { root = null; }...

  • In this assignment, you will add several methods to the Binary Search Tree. You should have compl...

    In this assignment, you will add several methods to the Binary Search Tree. You should have completed the following three methods in the lab: public void insert(Key key, Value value) public Value get(Key key) public void inorder(Node root) For this assignment, you will implement the following: public void remove(Node root, Key key) public Key getMin(Node n) public Key getMax(Node n) public int height(Node n) The main method contains the statements to check whether your implementation works. You need to change...

  • Please I need help ASAP Java Programing: Binary Search Tree Fully implement the BST class in Listing 25.4 (on page 961 of the 11th Edition of the text). Design and write a (main) driver program to com...

    Please I need help ASAP Java Programing: Binary Search Tree Fully implement the BST class in Listing 25.4 (on page 961 of the 11th Edition of the text). Design and write a (main) driver program to completely test every method in the BST class to ensure the class meets all its requirements. You should read the Listing 25.5: TestBST.java for an idea of what your program should look like. Listing 25.4 BST.java public class BST> extends AbstractTree { protected TreeNode...

  • Java help! Please help complete the min method below in bold. import java.util.Arrays; import java.util.ArrayList; import...

    Java help! Please help complete the min method below in bold. import java.util.Arrays; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; /** * Provides an implementation of a binary search tree * with no balance constraints, implemented with linked nodes. * * * */ public class Bst<T extends Comparable<T>> implements Iterable<T> { ////////////////////////////////////////////////////////////////// // I M P L E M E N T T H E M I N M E T H O D B E L O W...

  • package hw3; import java.util.LinkedList; /* *********************************************************************** * A simple BST with int keys and no values...

    package hw3; import java.util.LinkedList; /* *********************************************************************** * A simple BST with int keys and no values * * Complete each function below. * Write each function as a separate recursive definition (do not use more than one helper per function). * Depth of root==0. * Height of leaf==0. * Size of empty tree==0. * Height of empty tree=-1. * * TODO: complete the functions in this file. * DO NOT change the Node class. * DO NOT change the name...

  • Enum {FALSE=0, TRUE}; #define MAXBUFF 1024 #define SMALLBUFF 10 /* The LinkNode type is used as a...

    enum {FALSE=0, TRUE}; #define MAXBUFF 1024 #define SMALLBUFF 10 /* The LinkNode type is used as an element of a linked list ** implementation of a stack of tree nodes. */ typedef struct link_t LinkNode; typedef LinkNode *LinkNodePtr; /* The TreeNode type is used as an element of a binary "parse" tree. ** Tree nodes are created while parsing the RPN expression and ** stored on a stack until it's time to place them. */ typedef struct tree_t TreeNode; typedef...

  • Need this in C++ Goals: Your task is to implement a binary search tree of linked...

    Need this in C++ Goals: Your task is to implement a binary search tree of linked lists of movies. Tree nodes will contain a letter of the alphabet and a linked list. The linked list will be an alphabetically sorted list of movies which start with that letter. MovieTree() ➔ Constructor: Initialize any member variables of the class to default ~MovieTree() ➔ Destructor: Free all memory that was allocated void printMovieInventory() ➔ Print every movie in the data structure in...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT