Question

class AVLTree The following functions are the minimum requirements for the AVL class. You can add...

class AVLTree

The following functions are the minimum requirements for the AVL class. You can add any function from Assignment 2 to this class. You should modify the BSTree insert function so that the tree remains balanced after each insertion.

Required Public Member Functions

  • void insert(const string &): Insert an item to the binary search tree and perform rotation if necessary.
  • int balanceFactor(Node*): Return the balance factor of a given node.
  • void printBalanceFactors(): Traverse and print the tree in inorder notation. Print the string followed by its balance factor in parentheses followed by a , and one space.
  • void visualizeTree(const string &): Generate dotty file and visualize the tree using dotty program. Call this function before and after rotation.

Recommended Private Helper Functions

These helper functions are recommended, but you can change them or add other helper functions if necessary.

  • findUnbalancedNode: Find and return the closest unbalanced node (with balance factor of 2 or -2) to the inserted node.
  • rotate: Implement four possible imbalance cases and update the parent of the given node.
  • rotateLeft: Rotate the subtree to left at the given node and returns the new subroot.
  • rotateRight: Rotate the subtree to right at the given node and returns the new subroot.
  • void printBalanceFactors(Node *)
  • void visualizeTree(ofstream &, Node *)

Implementation of visualizeTree function

void BSTree::visualizeTree(const string &outputFilename){
    ofstream outFS(outputFilename.c_str());
    if(!outFS.is_open()){
        cout<<"Error"<<endl;
        return;
    }
    outFS<<"digraph G {"<<endl;
    visualizeTree(outFS,root);
    outFS<<"}";
    outFS.close();
    string jpgFilename = outputFilename.substr(0,outputFilename.size()-4)+".jpg";
    string command = "dot -Tjpg " + outputFilename + " -o " + jpgFilename;
    system(command.c_str());
}

void BSTree::visualizeTree(ofstream & outFS, Node *n){
    if(n){
        if(n->left){
            visualizeTree(outFS,n->left);
            outFS<<n->data <<" -> " <<n->left->data<<";"<<endl;    
        }

        if(n->right){
            visualizeTree(outFS,n->right);
            outFS<<n->data <<" -> " <<n->right->data<<";"<<endl;    
        }
    }
}

Use the following main to test your program.

#include <iostream>
#include "AVLTree.h"

using namespace std;

int menu() {
  int choice = 0;
  cout << endl << "Enter menu choice: ";
  cout << endl;
  cout 
    << "1. Insert" << endl
    << "2. Print" << endl
    << "3. Quit" << endl;
  cin >> choice;

  // fix buffer just in case non-numeric choice entered
  // also gets rid of newline character
  cin.clear();
  cin.ignore(256, '\n');
  return choice;
}

int main( ) {

  AVLTree tree;

  int choice = menu();

  string entry;

  while (choice != 3) {

    if (choice == 1) {
      cout << "Enter string to insert: ";
      getline(cin, entry);
      cout << endl;

      tree.insert(entry);

    } else if (choice == 2) {
      tree.printBalanceFactors();

    } 
    //fix buffer just in case non-numeric choice entered
    choice = menu();
  }

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

IF YOU HAVE ANY DOUBTS COMMENT BELOW WILL BE THERE TO HELP YOU

ANSWER:

CODE:

// C++ program to implement AVL Tree
#include<iostream>
#include<stdlib.h>
using namespace std;
  
// An AVL tree node
struct Node
{
char key;
struct Node *left;
struct Node *right;
int height;
};
  
// A utility function to get height of the tree
int height(struct Node *N)
{
if (N == NULL)
return 0;
return N->height;
}
  
// A utility function to get maximum of two integers
char max(char a, int b)
{
return (a > b)? a : b;
}
  
/* Helper function that allocates a new node with the given key and
NULL left and right pointers. */
struct Node* newNode(char key)
{
struct Node* node = (struct Node*)
malloc(sizeof(struct Node));
node->key = key;
node->left = NULL;
node->right = NULL;
node->height = 1; // new node is initially added at leaf
return(node);
}
  
// A utility function to right rotate subtree rooted with y
// See the diagram given above.
struct Node *rightRotate(struct Node *y)
{
struct Node *x = y->left;
struct Node *T2 = x->right;
  
// Perform rotation
x->right = y;
y->left = T2;
  
// Update heights
y->height = max(height(y->left), height(y->right))+1;
x->height = max(height(x->left), height(x->right))+1;
  
// Return new root
return x;
}
  
// A utility function to left rotate subtree rooted with x
// See the diagram given above.
struct Node *leftRotate(struct Node *x)
{
struct Node *y = x->right;
struct Node *T2 = y->left;
  
// Perform rotation
y->left = x;
x->right = T2;
  
// Update heights
x->height = max(height(x->left), height(x->right))+1;
y->height = max(height(y->left), height(y->right))+1;
  
// Return new root
return y;
}
  
// Get Balance factor of node N
int balanceFactor(struct Node *N)
{
if (N == NULL)
return 0;
return height(N->left) - height(N->right);
}
  
struct Node* insert(struct Node* node, char key)
{
/* 1. Perform the normal BST rotation */
if (node == NULL)
return(newNode(key));
  
if (key < node->key)
node->left = insert(node->left, key);
else if (key > node->key)
node->right = insert(node->right, key);
else // Equal keys not allowed
return node;
  
/* 2. Update height of this ancestor node */
node->height = 1 + max(height(node->left),
height(node->right));
  
/* 3. Get the balance factor of this ancestor
node to check whether this node became
unbalanced */
int balance = balanceFactor(node);
  
// If this node becomes unbalanced, then there are 4 cases
  
// Left Left Case
if (balance > 1 && key < node->left->key)
return rightRotate(node);
  
// Right Right Case
if (balance < -1 && key > node->right->key)
return leftRotate(node);
  
// Left Right Case
if (balance > 1 && key > node->left->key)
{
node->left = leftRotate(node->left);
return rightRotate(node);
}
  
// Right Left Case
if (balance < -1 && key < node->right->key)
{
node->right = rightRotate(node->right);
return leftRotate(node);
}
  
/* return the (unchanged) node pointer */
return node;
}
  
/* Given a non-empty binary search tree, return the
node with minimum key value found in that tree.
Note that the entire tree does not need to be
searched. */
struct Node * minValueNode(struct Node* node)
{
struct Node* current = node;
  
/* loop down to find the leftmost leaf */
while (current->left != NULL)
current = current->left;
  
return current;
}
  
  
// A utility function to print inorder traversal of
// the tree.

void inorder(struct Node *root)
{
if(root != NULL)
{
   inorder(root->left);
cout<< root->key;
inorder(root->right);
}
}

//A function that prints theinorder traversal of the tree and the balance factor within
// parenthesis followed by a, and a space
void printBalanceFactor(struct Node *root)
{
   cout<<"Inorder traversal of the constructed AVL tree is ";
inorder(root);
cout<<" ("<<balanceFactor(root)<<") a ";
}

/* Driver program to test above function*/
int main()
{
struct Node *root = NULL;
char ch;
char key;
do{
   cout<<"Want to insert?? (y/n): ";
   cin>>ch;
   if(ch=='y' || ch== 'Y')
   {
       cout<<"Enter data item..(character): ";
       cin>>key;
       root=insert(root,key);
   }
}while(ch=='y' || ch== 'Y');

printBalanceFactor(root);
return 0;
}

OUTPUT:

I request you to post another question for dotty program implementation, as it is insufficient to design so many functions within the allotted time.

HOPE IT HELPS YOU

RATE THUMBSUP PLEASE

Add a comment
Know the answer?
Add Answer to:
class AVLTree The following functions are the minimum requirements for the AVL class. You can add...
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++ 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....

  • Requirements: Finish all the functions which have been declared inside the hpp file. Details: st...

    Requirements: Finish all the functions which have been declared inside the hpp file. Details: string toString(void) const Return a visible list using '->' to show the linked relation which is a string like: 1->2->3->4->5->NULL void insert(int position, const int& data) Add an element at the given position: example0: 1->3->4->5->NULL instert(1, 2); 1->2->3->4->5->NULL example1: NULL insert(0, 1) 1->NULL void list::erase(int position) Erase the element at the given position 1->2->3->4->5->NULL erase(0) 2->3->4->5->NULL //main.cpp #include <iostream> #include <string> #include "SimpleList.hpp" using std::cin; using...

  • 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...

  • Hi there, I am working on a binary search tree code in c++. The program must...

    Hi there, I am working on a binary search tree code in c++. The program must store and update students' academic records, each node includes the student name, credits attempted, credits earned and GPA. I have made some progress with the code and written most of the functions in the .cpp file (already did the .h file) but i am struggling with what to put in the main and how to put an update part in the insert function. I...

  • Please use the linked approach implement the BST ADT, implement all the functions in the BSTree.cpp....

    Please use the linked approach implement the BST ADT, implement all the functions in the BSTree.cpp. Add the ouput of the implementation. use recursive functions to traverse the tree - read the implementation notes on using helper functions. Please use C++ programming ////////////////////////////////////////////////////////////// #include "BSTree.h" template <typename DataType, class KeyType> BSTree<DataType, KeyType>::BSTreeNode::BSTreeNode ( const DataType &nodeDataItem, BSTreeNode *leftPtr, BSTreeNode *rightPtr ) { } template < typename DataType, class KeyType > BSTree<DataType, KeyType>::BSTree () {    root = 0; } template...

  • For this lab, you will need to write the following functions in table.cpp, and add function...

    For this lab, you will need to write the following functions in table.cpp, and add function prototypes for them to table.h and invoke the functions in main.cpp. * int countNodes(node * root) Recursively count the number of the nodes in the tree. * int sumLeaves(node * root) Recursively sum all of the leaf nodes in the tree. You must use the functions with these exact function prototypes. ****************************************************************************** main.cpp #include "table.h" #include <iostream> using namespace std; int main() { node...

  • After the header, each line of the database file rebase210.txt contains the name of a restriction...

    After the header, each line of the database file rebase210.txt contains the name of a restriction enzyme and possible DNA sites the enzyme may cut (cut location is indicated by a ‘) in the following format: enzyme_acronym/recognition_sequence/…/recognition_sequence// For instance the first few lines of rebase210.txt are: AanI/TTA'TAA// AarI/CACCTGCNNNN'NNNN/'NNNNNNNNGCAGGTG// AasI/GACNNNN'NNGTC// AatII/GACGT'C// AbsI/CC'TCGAGG// AccI/GT'MKAC// AccII/CG'CG// AccIII/T'CCGGA// Acc16I/TGC'GCA// Acc36I/ACCTGCNNNN'NNNN/'NNNNNNNNGCAGGT// … That means that each line contains one enzyme acronym associated with one or more recognition sequences. For example on line 2:The enzyme acronym...

  • C++ (Using Binary Search Trees) other methods will result in downvote Implement the binary search tree...

    C++ (Using Binary Search Trees) other methods will result in downvote Implement the binary search tree methods (bst.cpp) for the binary search tree provided in the header file. Test your implementation with the included test. bst.h bst_test.cpp Note: Your implementation must correspond to declarations in the header file, and pass the test. Do not modify these two. I will compile your code against these. If the compilation fails, you will get down vote. bst.h #ifndef BINARY_SEARCH_TREE_H #define BINARY_SEARCH_TREE_H #include <string>...

  • C++ Help with Test #1 (at bottom) to work properly. May adjust code to work or...

    C++ Help with Test #1 (at bottom) to work properly. May adjust code to work or add any additional code. Do not use global variables. #include <iostream> #include <string> using std::endl; using std::cout; using std::cin; using std::string; void pressAnyKeyToContinue() { printf("Press any key to continue\n"); cin.get(); } //This helps with testing, do not modify. bool checkTest(string testName, int whatItShouldBe, int whatItIs) {    if (whatItShouldBe == whatItIs) { cout << "Passed " << testName << endl; return true; } else...

  • 3. (Gaddis Exercises 20.4) Tree Height Write a recursive member function for the BinaryTree class that...

    3. (Gaddis Exercises 20.4) Tree Height Write a recursive member function for the BinaryTree class that returns the height of the tree. The height of the tree is the number of levels it contains. Demonstrate the function in a driver program. CPP FILE CODE: #include "BinaryTree.h" #include <iostream> using namespace std; BinaryTree::BinaryTree() { root = NULL; } BinaryTree::~BinaryTree() { destroy(root); } bool BinaryTree::search(int data) { return search(data, root); } void BinaryTree::insert(int data) { insert(data, root); } void BinaryTree::traverseInOrder() { traverseInOrder(root);...

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