SlideShare a Scribd company logo
1 of 16
Download to read offline
I'm having trouble implementing a delete function for an AVL tree. I would like to use the
immediate successor approach as opposed to immediate predecessor. Can you help me out? Here
is my code:
template
class AVL_tree: public Search_tree {
public:
Error_code insert(const Record &new_data);
Error_code remove(const Record &old_data);
protected:
// Auxiliary functions
Error_code avl_insert(Binary_node* &sub_root, const Record &new_data, bool &taller);
Error_code avl_delete(Binary_node* &sub_root, const Record &old_data, bool &shorter);
//void avl_remove_root(Binary_node* &sub_root, bool &shorter, Record &predecessor,
Binary_node* &to_delete);
void left_balance(Binary_node* &sub_root);
void right_balance(Binary_node* &sub_root);
void rotate_left(Binary_node* &sub_root);
void rotate_right(Binary_node* &sub_root);
};
template
Error_code AVL_tree::insert(const Record &new_data)
/*
Post: If the key of new_data is already in the AVL_tree, a code
of duplicate_error is returned.
Otherwise, a code of success is returned and the Record new_data
is inserted into the tree in such a way that the properties of
an AVL tree are preserved.
Uses: avl_insert.
*/
{
bool taller;
//return avl_insert(this->root, new_data, taller);
return avl_insert(this->root, new_data, taller);
}
template
Error_code AVL_tree::remove(const Record &old_data)
/*
Post: If a Record with a key matching that of target belongs to the
AVL_tree, a code of success is returned, and the corresponding node
is removed from the tree. Otherwise, a code of not_present is returned.
Uses: Function search_and_destroy
*/
{
bool shorter;
return avl_delete(this->root, old_data, shorter);
}
template
Error_code AVL_tree::avl_insert(Binary_node* &sub_root,
const Record &new_data, bool &taller)
/*
Pre: sub_root is either NULL or points to a subtree of the AVL_tree
Post: If the key of new_data is already in the subtree, a
code of duplicate_error is returned.
Otherwise, a code of success is returned and the Record new_data
is inserted into the subtree in such a way that the
properties of an AVL tree have been preserved.
If the subtree is increased in height, the parameter taller is set to
true; otherwise it is set to false.
Uses: Methods of struct AVL_node; functions avl_insert
recursively, left_balance, and right_balance.
*/
{
Error_code result = success;
if (sub_root == NULL) {
sub_root = new AVL_node(new_data);
taller = true; //taller is true for every new node creation
}
else if (new_data == sub_root->data) {
result = duplicate_error;
taller = false;
}
//insert to LST
else if (new_data < sub_root->data) {
result = avl_insert(sub_root->left, new_data, taller);
if (taller == true)
switch (sub_root->get_balance()) {
case left_higher: //lh before insertion, now unbalanced
left_balance(sub_root);
taller = false;
break;
case equal_height:
sub_root->set_balance(left_higher);
break;
case right_higher:
sub_root->set_balance(equal_height);
taller = false;
break;
}
}
//insert to RST
else {
result = avl_insert(sub_root->right, new_data, taller);
if (taller == true)
switch (sub_root->get_balance()) {
case left_higher:
sub_root->set_balance(equal_height);
taller = false;
break;
case equal_height:
sub_root->set_balance(right_higher);
break;
case right_higher:
right_balance(sub_root);
taller = false;
break;
}
}
return result;
}
template
Error_code AVL_tree::avl_delete(Binary_node* &sub_root,
const Record &old_data, bool &shorter)
{
Error_code result = success;
Binary_node *temp;
if (sub_root == NULL) {
result = not_present;
shorter = false;
}
else if (old_data == sub_root->data) {
Binary_node *to_delete = sub_root;
shorter = true;
if (sub_root->right == NULL) {
sub_root = sub_root->left;
}
else if (sub_root->left == NULL) {
sub_root = sub_root->right;
}
else {
to_delete = sub_root->right;
Binary_node *parent = sub_root;
while (to_delete->left != NULL) {
parent = to_delete;
to_delete = to_delete->left;
}
sub_root->data = to_delete->data;
if (parent == sub_root) {
sub_root->right = to_delete->right;
}
else {
parent->left = to_delete->right;
}
}
delete to_delete;
}
else if (old_data < sub_root->data) {
result = avl_delete(sub_root->left, old_data, shorter);
if (shorter == true)
switch (sub_root->get_balance()) {
case left_higher:
sub_root->set_balance(equal_height);
shorter = true;
break;
case equal_height:
sub_root->set_balance(right_higher);
shorter = false;
break;
case right_higher:
temp = sub_root->right;
if (temp->get_balance() == equal_height) {
shorter = true;
}
else {
shorter = false;
}
right_balance(sub_root);
break;
}
}
else {
result = avl_delete(sub_root->right, old_data, shorter);
if (shorter == true)
switch (sub_root->get_balance()) {
case left_higher:
temp = sub_root->left;
if (temp->get_balance() == equal_height) {
shorter = true;
}
else {
shorter = false;
}
left_balance(sub_root);
break;
case equal_height:
sub_root->set_balance(left_higher);
shorter = false;
break;
case right_higher:
sub_root->set_balance(equal_height);
shorter = true;
break;
}
}
return result;
}
template
void AVL_tree::left_balance(Binary_node* &sub_root)
/*
Pre: sub_root points to a subtree of an AVL_tree that
is doubly unbalanced on the left.
Post: The AVL properties have been restored to the subtree.
Uses:
*/
{
}
template
void AVL_tree::right_balance(Binary_node *&sub_root)
/*
Pre: sub_root points to a subtree of an AVL_tree that
is unbalanced on the right.
Post: The AVL properties have been restored to the subtree.
Uses: Methods of struct AVL_node;
functions rotate_right and rotate_left.
*/
{
Binary_node* &right_tree = sub_root->right;
// case right_higher: sigle left rotation
// O ub --> subroot
// 
// O rh --> right_tree
// 
// O
switch (right_tree->get_balance()) {
case right_higher: // single left rotation
sub_root->set_balance(equal_height);
right_tree->set_balance(equal_height);
rotate_left(sub_root); //pointer adjustment
break;
case equal_height: // impossible case
cout << "WARNING: If you see this in an insertion, program error is detected in
right_balance" << endl;
right_tree->set_balance(left_higher);
rotate_left(sub_root);
break;
// case left_higher: double rotation left
// O ub --> sub_root
// 
// O lh --> right_tree
// /
// O three cases --> sub_tree
case left_higher:
Binary_node *sub_tree = right_tree->left;
//set balance of sub_root and right_tree assuming rotation is done
switch (sub_tree->get_balance()) {
case equal_height:
sub_root->set_balance(equal_height);
right_tree->set_balance(equal_height);
break;
case left_higher:
sub_root->set_balance(equal_height);
right_tree->set_balance(right_higher);
break;
case right_higher:
sub_root->set_balance(left_higher);
right_tree->set_balance(equal_height);
break;
}
//set balance of sub_tree after rotation
sub_tree->set_balance(equal_height);
//perform actual rotation
rotate_right(right_tree);
rotate_left(sub_root);
break;
}
}
//adjustment of pointers
template
void AVL_tree::rotate_left(Binary_node *&sub_root)
/*
Pre: sub_root points to a subtree of the AVL_tree.
This subtree has a nonempty right subtree.
Post: sub_root is reset to point to its former right child, and the former
sub_root node is the left child of the new sub_root node.
*/
{
if (sub_root == NULL || sub_root->right == NULL) // impossible cases
cout << "WARNING: program error detected in rotate_left" << endl;
else {
Binary_node *right_tree = sub_root->right;
sub_root->right = right_tree->left;
right_tree->left = sub_root;
sub_root = right_tree;
}
}
template
void AVL_tree::rotate_right(Binary_node *&sub_root)
/*
Pre: sub_root points to a subtree of the AVL_tree.
This subtree has a nonempty left subtree.
Post:
*/
{
}
Solution
My Code:
/* AVL node */
template
class AVLnode {
public:
T key;
int balance;
AVLnode *left, *right, *parent;
AVLnode(T k, AVLnode *p) : key(k), balance(0), parent(p),
left(NULL), right(NULL) {}
~AVLnode() {
delete left;
delete right;
}
};
/* AVL tree */
template
class AVLtree {
public:
AVLtree(void);
~AVLtree(void);
bool insert(T key);
void deleteKey(const T key);
void printBalance();
private:
AVLnode *root;
AVLnode* rotateLeft ( AVLnode *a );
AVLnode* rotateRight ( AVLnode *a );
AVLnode* rotateLeftThenRight ( AVLnode *n );
AVLnode* rotateRightThenLeft ( AVLnode *n );
void rebalance ( AVLnode *n );
int height ( AVLnode *n );
void setBalance ( AVLnode *n );
void printBalance ( AVLnode *n );
void clearNode ( AVLnode *n );
};
/* AVL class definition */
template
void AVLtree::rebalance(AVLnode *n) {
setBalance(n);
if (n->balance == -2) {
if (height(n->left->left) >= height(n->left->right))
n = rotateRight(n);
else
n = rotateLeftThenRight(n);
}
else if (n->balance == 2) {
if (height(n->right->right) >= height(n->right->left))
n = rotateLeft(n);
else
n = rotateRightThenLeft(n);
}
if (n->parent != NULL) {
rebalance(n->parent);
}
else {
root = n;
}
}
template
AVLnode* AVLtree::rotateLeft(AVLnode *a) {
AVLnode *b = a->right;
b->parent = a->parent;
a->right = b->left;
if (a->right != NULL)
a->right->parent = a;
b->left = a;
a->parent = b;
if (b->parent != NULL) {
if (b->parent->right == a) {
b->parent->right = b;
}
else {
b->parent->left = b;
}
}
setBalance(a);
setBalance(b);
return b;
}
template
AVLnode* AVLtree::rotateRight(AVLnode *a) {
AVLnode *b = a->left;
b->parent = a->parent;
a->left = b->right;
if (a->left != NULL)
a->left->parent = a;
b->right = a;
a->parent = b;
if (b->parent != NULL) {
if (b->parent->right == a) {
b->parent->right = b;
}
else {
b->parent->left = b;
}
}
setBalance(a);
setBalance(b);
return b;
}
template
AVLnode* AVLtree::rotateLeftThenRight(AVLnode *n) {
n->left = rotateLeft(n->left);
return rotateRight(n);
}
template
AVLnode* AVLtree::rotateRightThenLeft(AVLnode *n) {
n->right = rotateRight(n->right);
return rotateLeft(n);
}
template
int AVLtree::height(AVLnode *n) {
if (n == NULL)
return -1;
return 1 + std::max(height(n->left), height(n->right));
}
template
void AVLtree::setBalance(AVLnode *n) {
n->balance = height(n->right) - height(n->left);
}
template
void AVLtree::printBalance(AVLnode *n) {
if (n != NULL) {
printBalance(n->left);
std::cout << n->balance << " ";
printBalance(n->right);
}
}
template
AVLtree::AVLtree(void) : root(NULL) {}
template
AVLtree::~AVLtree(void) {
delete root;
}
template
bool AVLtree::insert(T key) {
if (root == NULL) {
root = new AVLnode(key, NULL);
}
else {
AVLnode
*n = root,
*parent;
while (true) {
if (n->key == key)
return false;
parent = n;
bool goLeft = n->key > key;
n = goLeft ? n->left : n->right;
if (n == NULL) {
if (goLeft) {
parent->left = new AVLnode(key, parent);
}
else {
parent->right = new AVLnode(key, parent);
}
rebalance(parent);
break;
}
}
}
return true;
}
template
void AVLtree::deleteKey(const T delKey) {
if (root == NULL)
return;
AVLnode
*n = root,
*parent = root,
*delNode = NULL,
*child = root;
while (child != NULL) {
parent = n;
n = child;
child = delKey >= n->key ? n->right : n->left;
if (delKey == n->key)
delNode = n;
}
if (delNode != NULL) {
delNode->key = n->key;
child = n->left != NULL ? n->left : n->right;
if (root->key == delKey) {
root = child;
}
else {
if(parent->left == n){
parent->left = child;
}
else {
parent->right = child;
}
rebalance(parent);
}
}
}
template
void AVLtree::printBalance() {
printBalance(root);
std::cout << std::endl;
}

More Related Content

Similar to Im having trouble implementing a delete function for an AVL tree. .pdf

C programming. Answer question only in C code Ninth Deletion with B.pdf
C programming. Answer question only in C code Ninth Deletion with B.pdfC programming. Answer question only in C code Ninth Deletion with B.pdf
C programming. Answer question only in C code Ninth Deletion with B.pdf
info309708
 
For this project, write a program that stores integers in a binary.docx
For this project, write a program that stores integers in a binary.docxFor this project, write a program that stores integers in a binary.docx
For this project, write a program that stores integers in a binary.docx
budbarber38650
 
Need Help with this Java Assignment. Program should be done in JAVA .pdf
Need Help with this Java Assignment. Program should be done in JAVA .pdfNeed Help with this Java Assignment. Program should be done in JAVA .pdf
Need Help with this Java Assignment. Program should be done in JAVA .pdf
archiesgallery
 
03.DS_Store__MACOSX03._.DS_Store03A2.DS_Store__.docx
03.DS_Store__MACOSX03._.DS_Store03A2.DS_Store__.docx03.DS_Store__MACOSX03._.DS_Store03A2.DS_Store__.docx
03.DS_Store__MACOSX03._.DS_Store03A2.DS_Store__.docx
honey725342
 
Assg 12 Binary Search Trees COSC 2336assg-12.cppAssg 12 Binary .docx
Assg 12 Binary Search Trees COSC 2336assg-12.cppAssg 12 Binary .docxAssg 12 Binary Search Trees COSC 2336assg-12.cppAssg 12 Binary .docx
Assg 12 Binary Search Trees COSC 2336assg-12.cppAssg 12 Binary .docx
festockton
 
JavaCreate a java application using the code example in the follo.pdf
JavaCreate a java application using the code example in the follo.pdfJavaCreate a java application using the code example in the follo.pdf
JavaCreate a java application using the code example in the follo.pdf
ambersushil
 
Templated Binary Tree implementing function help I need to im.pdf
Templated Binary Tree implementing function help I need to im.pdfTemplated Binary Tree implementing function help I need to im.pdf
Templated Binary Tree implementing function help I need to im.pdf
manjan6
 
Add to BST.java a method height() that computes the height of the tr.pdf
Add to BST.java a method height() that computes the height of the tr.pdfAdd to BST.java a method height() that computes the height of the tr.pdf
Add to BST.java a method height() that computes the height of the tr.pdf
flashfashioncasualwe
 
So I have this code(StackInAllSocks) and I implemented the method but.pdf
So I have this code(StackInAllSocks) and I implemented the method but.pdfSo I have this code(StackInAllSocks) and I implemented the method but.pdf
So I have this code(StackInAllSocks) and I implemented the method but.pdf
aksahnan
 
Modify this code to do an Insert function for an AVL tree, instead o.pdf
Modify this code to do an Insert function for an AVL tree, instead o.pdfModify this code to do an Insert function for an AVL tree, instead o.pdf
Modify this code to do an Insert function for an AVL tree, instead o.pdf
fathimaoptical
 
Define a class template for an AVL tree. Create an object of su.pdf
Define a class template for an AVL tree. Create an object of su.pdfDefine a class template for an AVL tree. Create an object of su.pdf
Define a class template for an AVL tree. Create an object of su.pdf
eyelineoptics
 
Please write in C++ and should be able to compile and debug.Thank yo.pdf
Please write in C++ and should be able to compile and debug.Thank yo.pdfPlease write in C++ and should be able to compile and debug.Thank yo.pdf
Please write in C++ and should be able to compile and debug.Thank yo.pdf
ajaycosmeticslg
 
Day2 Verilog HDL Basic
Day2 Verilog HDL BasicDay2 Verilog HDL Basic
Day2 Verilog HDL Basic
Ron Liu
 
write a method to generate AVL tree of height h wth fewest nodes and.pdf
write a method to generate AVL tree of height h wth fewest nodes and.pdfwrite a method to generate AVL tree of height h wth fewest nodes and.pdf
write a method to generate AVL tree of height h wth fewest nodes and.pdf
arcotstarsports
 
b. (10 pts) Implement the rotate left method for AVL trees.c. (10 .pdf
b. (10 pts) Implement the rotate left method for AVL trees.c. (10 .pdfb. (10 pts) Implement the rotate left method for AVL trees.c. (10 .pdf
b. (10 pts) Implement the rotate left method for AVL trees.c. (10 .pdf
akanshanawal
 
Assignment 9 (Parent reference for BST) Redefine TreeNode by adding .pdf
Assignment 9 (Parent reference for BST) Redefine TreeNode by adding .pdfAssignment 9 (Parent reference for BST) Redefine TreeNode by adding .pdf
Assignment 9 (Parent reference for BST) Redefine TreeNode by adding .pdf
Footageetoffe16
 

Similar to Im having trouble implementing a delete function for an AVL tree. .pdf (20)

C programming. Answer question only in C code Ninth Deletion with B.pdf
C programming. Answer question only in C code Ninth Deletion with B.pdfC programming. Answer question only in C code Ninth Deletion with B.pdf
C programming. Answer question only in C code Ninth Deletion with B.pdf
 
For this project, write a program that stores integers in a binary.docx
For this project, write a program that stores integers in a binary.docxFor this project, write a program that stores integers in a binary.docx
For this project, write a program that stores integers in a binary.docx
 
Php Chapter 1 Training
Php Chapter 1 TrainingPhp Chapter 1 Training
Php Chapter 1 Training
 
Need Help with this Java Assignment. Program should be done in JAVA .pdf
Need Help with this Java Assignment. Program should be done in JAVA .pdfNeed Help with this Java Assignment. Program should be done in JAVA .pdf
Need Help with this Java Assignment. Program should be done in JAVA .pdf
 
03.DS_Store__MACOSX03._.DS_Store03A2.DS_Store__.docx
03.DS_Store__MACOSX03._.DS_Store03A2.DS_Store__.docx03.DS_Store__MACOSX03._.DS_Store03A2.DS_Store__.docx
03.DS_Store__MACOSX03._.DS_Store03A2.DS_Store__.docx
 
Assg 12 Binary Search Trees COSC 2336assg-12.cppAssg 12 Binary .docx
Assg 12 Binary Search Trees COSC 2336assg-12.cppAssg 12 Binary .docxAssg 12 Binary Search Trees COSC 2336assg-12.cppAssg 12 Binary .docx
Assg 12 Binary Search Trees COSC 2336assg-12.cppAssg 12 Binary .docx
 
JavaCreate a java application using the code example in the follo.pdf
JavaCreate a java application using the code example in the follo.pdfJavaCreate a java application using the code example in the follo.pdf
JavaCreate a java application using the code example in the follo.pdf
 
Templated Binary Tree implementing function help I need to im.pdf
Templated Binary Tree implementing function help I need to im.pdfTemplated Binary Tree implementing function help I need to im.pdf
Templated Binary Tree implementing function help I need to im.pdf
 
Add to BST.java a method height() that computes the height of the tr.pdf
Add to BST.java a method height() that computes the height of the tr.pdfAdd to BST.java a method height() that computes the height of the tr.pdf
Add to BST.java a method height() that computes the height of the tr.pdf
 
So I have this code(StackInAllSocks) and I implemented the method but.pdf
So I have this code(StackInAllSocks) and I implemented the method but.pdfSo I have this code(StackInAllSocks) and I implemented the method but.pdf
So I have this code(StackInAllSocks) and I implemented the method but.pdf
 
Modify this code to do an Insert function for an AVL tree, instead o.pdf
Modify this code to do an Insert function for an AVL tree, instead o.pdfModify this code to do an Insert function for an AVL tree, instead o.pdf
Modify this code to do an Insert function for an AVL tree, instead o.pdf
 
Define a class template for an AVL tree. Create an object of su.pdf
Define a class template for an AVL tree. Create an object of su.pdfDefine a class template for an AVL tree. Create an object of su.pdf
Define a class template for an AVL tree. Create an object of su.pdf
 
Please write in C++ and should be able to compile and debug.Thank yo.pdf
Please write in C++ and should be able to compile and debug.Thank yo.pdfPlease write in C++ and should be able to compile and debug.Thank yo.pdf
Please write in C++ and should be able to compile and debug.Thank yo.pdf
 
Day2 Verilog HDL Basic
Day2 Verilog HDL BasicDay2 Verilog HDL Basic
Day2 Verilog HDL Basic
 
write a method to generate AVL tree of height h wth fewest nodes and.pdf
write a method to generate AVL tree of height h wth fewest nodes and.pdfwrite a method to generate AVL tree of height h wth fewest nodes and.pdf
write a method to generate AVL tree of height h wth fewest nodes and.pdf
 
b. (10 pts) Implement the rotate left method for AVL trees.c. (10 .pdf
b. (10 pts) Implement the rotate left method for AVL trees.c. (10 .pdfb. (10 pts) Implement the rotate left method for AVL trees.c. (10 .pdf
b. (10 pts) Implement the rotate left method for AVL trees.c. (10 .pdf
 
Arduino Section Programming - from Sparkfun
Arduino Section Programming - from SparkfunArduino Section Programming - from Sparkfun
Arduino Section Programming - from Sparkfun
 
Data Types and Processing in ES6
Data Types and Processing in ES6Data Types and Processing in ES6
Data Types and Processing in ES6
 
Assignment 9 (Parent reference for BST) Redefine TreeNode by adding .pdf
Assignment 9 (Parent reference for BST) Redefine TreeNode by adding .pdfAssignment 9 (Parent reference for BST) Redefine TreeNode by adding .pdf
Assignment 9 (Parent reference for BST) Redefine TreeNode by adding .pdf
 
Discuss about Header Node And also write a program for unordered si.pdf
Discuss about Header Node  And also write a program for unordered si.pdfDiscuss about Header Node  And also write a program for unordered si.pdf
Discuss about Header Node And also write a program for unordered si.pdf
 

More from sktambifortune

Your company is preparing to migrate from IPv4 to IPv6, and you are .pdf
Your company is preparing to migrate from IPv4 to IPv6, and you are .pdfYour company is preparing to migrate from IPv4 to IPv6, and you are .pdf
Your company is preparing to migrate from IPv4 to IPv6, and you are .pdf
sktambifortune
 
You are burning the latest song you bought on ITunes to a disk. The .pdf
You are burning the latest song you bought on ITunes to a disk. The .pdfYou are burning the latest song you bought on ITunes to a disk. The .pdf
You are burning the latest song you bought on ITunes to a disk. The .pdf
sktambifortune
 
CASE 3-12 Information System Project Steering Committee The Informat.pdf
CASE 3-12 Information System Project Steering Committee The Informat.pdfCASE 3-12 Information System Project Steering Committee The Informat.pdf
CASE 3-12 Information System Project Steering Committee The Informat.pdf
sktambifortune
 
Assignment of SOS operating systemThe file lmemman.c has one incom.pdf
Assignment of SOS operating systemThe file lmemman.c has one incom.pdfAssignment of SOS operating systemThe file lmemman.c has one incom.pdf
Assignment of SOS operating systemThe file lmemman.c has one incom.pdf
sktambifortune
 
Any kind of help would gladly be appreciated. (C-programming)Probl.pdf
Any kind of help would gladly be appreciated. (C-programming)Probl.pdfAny kind of help would gladly be appreciated. (C-programming)Probl.pdf
Any kind of help would gladly be appreciated. (C-programming)Probl.pdf
sktambifortune
 
what are three effects of transistor scaling on computer architectur.pdf
what are three effects of transistor scaling on computer architectur.pdfwhat are three effects of transistor scaling on computer architectur.pdf
what are three effects of transistor scaling on computer architectur.pdf
sktambifortune
 
What are some of the motives for employee theft What are some .pdf
What are some of the motives for employee theft What are some .pdfWhat are some of the motives for employee theft What are some .pdf
What are some of the motives for employee theft What are some .pdf
sktambifortune
 
The Puritan faith community shaped the New England colonies in virtu.pdf
The Puritan faith community shaped the New England colonies in virtu.pdfThe Puritan faith community shaped the New England colonies in virtu.pdf
The Puritan faith community shaped the New England colonies in virtu.pdf
sktambifortune
 
savings account d. the value of the shares is based on the amount of .pdf
savings account d. the value of the shares is based on the amount of .pdfsavings account d. the value of the shares is based on the amount of .pdf
savings account d. the value of the shares is based on the amount of .pdf
sktambifortune
 
QuestionIt was reported on June 11, 1997, by NBC Nightly News that.pdf
QuestionIt was reported on June 11, 1997, by NBC Nightly News that.pdfQuestionIt was reported on June 11, 1997, by NBC Nightly News that.pdf
QuestionIt was reported on June 11, 1997, by NBC Nightly News that.pdf
sktambifortune
 
946 LTE Labs Le.chateliers-lab.pdf Before beginning this experiment.pdf
946 LTE Labs Le.chateliers-lab.pdf  Before beginning this experiment.pdf946 LTE Labs Le.chateliers-lab.pdf  Before beginning this experiment.pdf
946 LTE Labs Le.chateliers-lab.pdf Before beginning this experiment.pdf
sktambifortune
 
4. Refer to the table of Gini coefficients in the Added Dimension box.pdf
4. Refer to the table of Gini coefficients in the Added Dimension box.pdf4. Refer to the table of Gini coefficients in the Added Dimension box.pdf
4. Refer to the table of Gini coefficients in the Added Dimension box.pdf
sktambifortune
 

More from sktambifortune (20)

Your company is preparing to migrate from IPv4 to IPv6, and you are .pdf
Your company is preparing to migrate from IPv4 to IPv6, and you are .pdfYour company is preparing to migrate from IPv4 to IPv6, and you are .pdf
Your company is preparing to migrate from IPv4 to IPv6, and you are .pdf
 
You are burning the latest song you bought on ITunes to a disk. The .pdf
You are burning the latest song you bought on ITunes to a disk. The .pdfYou are burning the latest song you bought on ITunes to a disk. The .pdf
You are burning the latest song you bought on ITunes to a disk. The .pdf
 
CASE 3-12 Information System Project Steering Committee The Informat.pdf
CASE 3-12 Information System Project Steering Committee The Informat.pdfCASE 3-12 Information System Project Steering Committee The Informat.pdf
CASE 3-12 Information System Project Steering Committee The Informat.pdf
 
Can you date the latest financial crisis in the United States or in .pdf
Can you date the latest financial crisis in the United States or in .pdfCan you date the latest financial crisis in the United States or in .pdf
Can you date the latest financial crisis in the United States or in .pdf
 
B1. State the components of organization. Give good examples to justi.pdf
B1. State the components of organization. Give good examples to justi.pdfB1. State the components of organization. Give good examples to justi.pdf
B1. State the components of organization. Give good examples to justi.pdf
 
Assignment of SOS operating systemThe file lmemman.c has one incom.pdf
Assignment of SOS operating systemThe file lmemman.c has one incom.pdfAssignment of SOS operating systemThe file lmemman.c has one incom.pdf
Assignment of SOS operating systemThe file lmemman.c has one incom.pdf
 
Any kind of help would gladly be appreciated. (C-programming)Probl.pdf
Any kind of help would gladly be appreciated. (C-programming)Probl.pdfAny kind of help would gladly be appreciated. (C-programming)Probl.pdf
Any kind of help would gladly be appreciated. (C-programming)Probl.pdf
 
Which of the following solutions will turn red litmus blue pOH 1.pdf
Which of the following solutions will turn red litmus blue pOH 1.pdfWhich of the following solutions will turn red litmus blue pOH 1.pdf
Which of the following solutions will turn red litmus blue pOH 1.pdf
 
What serves as the most reliable source of information about the .pdf
What serves as the most reliable source of information about the .pdfWhat serves as the most reliable source of information about the .pdf
What serves as the most reliable source of information about the .pdf
 
What is the difference between the terms “earnings and profits” and .pdf
What is the difference between the terms “earnings and profits” and .pdfWhat is the difference between the terms “earnings and profits” and .pdf
What is the difference between the terms “earnings and profits” and .pdf
 
what are three effects of transistor scaling on computer architectur.pdf
what are three effects of transistor scaling on computer architectur.pdfwhat are three effects of transistor scaling on computer architectur.pdf
what are three effects of transistor scaling on computer architectur.pdf
 
What are some of the motives for employee theft What are some .pdf
What are some of the motives for employee theft What are some .pdfWhat are some of the motives for employee theft What are some .pdf
What are some of the motives for employee theft What are some .pdf
 
Twitter is a popular social media. It allows its users to exchange tw.pdf
Twitter is a popular social media. It allows its users to exchange tw.pdfTwitter is a popular social media. It allows its users to exchange tw.pdf
Twitter is a popular social media. It allows its users to exchange tw.pdf
 
A. State the domai and ranga. 1. y find the inverse and state the dom.pdf
A. State the domai and ranga. 1. y find the inverse and state the dom.pdfA. State the domai and ranga. 1. y find the inverse and state the dom.pdf
A. State the domai and ranga. 1. y find the inverse and state the dom.pdf
 
The Puritan faith community shaped the New England colonies in virtu.pdf
The Puritan faith community shaped the New England colonies in virtu.pdfThe Puritan faith community shaped the New England colonies in virtu.pdf
The Puritan faith community shaped the New England colonies in virtu.pdf
 
savings account d. the value of the shares is based on the amount of .pdf
savings account d. the value of the shares is based on the amount of .pdfsavings account d. the value of the shares is based on the amount of .pdf
savings account d. the value of the shares is based on the amount of .pdf
 
QuestionIt was reported on June 11, 1997, by NBC Nightly News that.pdf
QuestionIt was reported on June 11, 1997, by NBC Nightly News that.pdfQuestionIt was reported on June 11, 1997, by NBC Nightly News that.pdf
QuestionIt was reported on June 11, 1997, by NBC Nightly News that.pdf
 
946 LTE Labs Le.chateliers-lab.pdf Before beginning this experiment.pdf
946 LTE Labs Le.chateliers-lab.pdf  Before beginning this experiment.pdf946 LTE Labs Le.chateliers-lab.pdf  Before beginning this experiment.pdf
946 LTE Labs Le.chateliers-lab.pdf Before beginning this experiment.pdf
 
Prove that the T_i-property is a topological property for i = 0So.pdf
Prove that the T_i-property is a topological property for i = 0So.pdfProve that the T_i-property is a topological property for i = 0So.pdf
Prove that the T_i-property is a topological property for i = 0So.pdf
 
4. Refer to the table of Gini coefficients in the Added Dimension box.pdf
4. Refer to the table of Gini coefficients in the Added Dimension box.pdf4. Refer to the table of Gini coefficients in the Added Dimension box.pdf
4. Refer to the table of Gini coefficients in the Added Dimension box.pdf
 

Recently uploaded

SPLICE Working Group: Reusable Code Examples
SPLICE Working Group:Reusable Code ExamplesSPLICE Working Group:Reusable Code Examples
SPLICE Working Group: Reusable Code Examples
Peter Brusilovsky
 
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
中 央社
 

Recently uploaded (20)

Improved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio AppImproved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio App
 
UChicago CMSC 23320 - The Best Commit Messages of 2024
UChicago CMSC 23320 - The Best Commit Messages of 2024UChicago CMSC 23320 - The Best Commit Messages of 2024
UChicago CMSC 23320 - The Best Commit Messages of 2024
 
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
 
An Overview of the Odoo 17 Knowledge App
An Overview of the Odoo 17 Knowledge AppAn Overview of the Odoo 17 Knowledge App
An Overview of the Odoo 17 Knowledge App
 
Book Review of Run For Your Life Powerpoint
Book Review of Run For Your Life PowerpointBook Review of Run For Your Life Powerpoint
Book Review of Run For Your Life Powerpoint
 
SPLICE Working Group: Reusable Code Examples
SPLICE Working Group:Reusable Code ExamplesSPLICE Working Group:Reusable Code Examples
SPLICE Working Group: Reusable Code Examples
 
VAMOS CUIDAR DO NOSSO PLANETA! .
VAMOS CUIDAR DO NOSSO PLANETA!                    .VAMOS CUIDAR DO NOSSO PLANETA!                    .
VAMOS CUIDAR DO NOSSO PLANETA! .
 
Spring gala 2024 photo slideshow - Celebrating School-Community Partnerships
Spring gala 2024 photo slideshow - Celebrating School-Community PartnershipsSpring gala 2024 photo slideshow - Celebrating School-Community Partnerships
Spring gala 2024 photo slideshow - Celebrating School-Community Partnerships
 
Mattingly "AI & Prompt Design: Named Entity Recognition"
Mattingly "AI & Prompt Design: Named Entity Recognition"Mattingly "AI & Prompt Design: Named Entity Recognition"
Mattingly "AI & Prompt Design: Named Entity Recognition"
 
PSYPACT- Practicing Over State Lines May 2024.pptx
PSYPACT- Practicing Over State Lines May 2024.pptxPSYPACT- Practicing Over State Lines May 2024.pptx
PSYPACT- Practicing Over State Lines May 2024.pptx
 
An overview of the various scriptures in Hinduism
An overview of the various scriptures in HinduismAn overview of the various scriptures in Hinduism
An overview of the various scriptures in Hinduism
 
How To Create Editable Tree View in Odoo 17
How To Create Editable Tree View in Odoo 17How To Create Editable Tree View in Odoo 17
How To Create Editable Tree View in Odoo 17
 
Observing-Correct-Grammar-in-Making-Definitions.pptx
Observing-Correct-Grammar-in-Making-Definitions.pptxObserving-Correct-Grammar-in-Making-Definitions.pptx
Observing-Correct-Grammar-in-Making-Definitions.pptx
 
Andreas Schleicher presents at the launch of What does child empowerment mean...
Andreas Schleicher presents at the launch of What does child empowerment mean...Andreas Schleicher presents at the launch of What does child empowerment mean...
Andreas Schleicher presents at the launch of What does child empowerment mean...
 
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdfFICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
 
Including Mental Health Support in Project Delivery, 14 May.pdf
Including Mental Health Support in Project Delivery, 14 May.pdfIncluding Mental Health Support in Project Delivery, 14 May.pdf
Including Mental Health Support in Project Delivery, 14 May.pdf
 
8 Tips for Effective Working Capital Management
8 Tips for Effective Working Capital Management8 Tips for Effective Working Capital Management
8 Tips for Effective Working Capital Management
 
Basic Civil Engineering notes on Transportation Engineering & Modes of Transport
Basic Civil Engineering notes on Transportation Engineering & Modes of TransportBasic Civil Engineering notes on Transportation Engineering & Modes of Transport
Basic Civil Engineering notes on Transportation Engineering & Modes of Transport
 
Analyzing and resolving a communication crisis in Dhaka textiles LTD.pptx
Analyzing and resolving a communication crisis in Dhaka textiles LTD.pptxAnalyzing and resolving a communication crisis in Dhaka textiles LTD.pptx
Analyzing and resolving a communication crisis in Dhaka textiles LTD.pptx
 
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
 

Im having trouble implementing a delete function for an AVL tree. .pdf

  • 1. I'm having trouble implementing a delete function for an AVL tree. I would like to use the immediate successor approach as opposed to immediate predecessor. Can you help me out? Here is my code: template class AVL_tree: public Search_tree { public: Error_code insert(const Record &new_data); Error_code remove(const Record &old_data); protected: // Auxiliary functions Error_code avl_insert(Binary_node* &sub_root, const Record &new_data, bool &taller); Error_code avl_delete(Binary_node* &sub_root, const Record &old_data, bool &shorter); //void avl_remove_root(Binary_node* &sub_root, bool &shorter, Record &predecessor, Binary_node* &to_delete); void left_balance(Binary_node* &sub_root); void right_balance(Binary_node* &sub_root); void rotate_left(Binary_node* &sub_root); void rotate_right(Binary_node* &sub_root); }; template Error_code AVL_tree::insert(const Record &new_data) /* Post: If the key of new_data is already in the AVL_tree, a code of duplicate_error is returned. Otherwise, a code of success is returned and the Record new_data is inserted into the tree in such a way that the properties of an AVL tree are preserved. Uses: avl_insert. */ { bool taller; //return avl_insert(this->root, new_data, taller); return avl_insert(this->root, new_data, taller); }
  • 2. template Error_code AVL_tree::remove(const Record &old_data) /* Post: If a Record with a key matching that of target belongs to the AVL_tree, a code of success is returned, and the corresponding node is removed from the tree. Otherwise, a code of not_present is returned. Uses: Function search_and_destroy */ { bool shorter; return avl_delete(this->root, old_data, shorter); } template Error_code AVL_tree::avl_insert(Binary_node* &sub_root, const Record &new_data, bool &taller) /* Pre: sub_root is either NULL or points to a subtree of the AVL_tree Post: If the key of new_data is already in the subtree, a code of duplicate_error is returned. Otherwise, a code of success is returned and the Record new_data is inserted into the subtree in such a way that the properties of an AVL tree have been preserved. If the subtree is increased in height, the parameter taller is set to true; otherwise it is set to false. Uses: Methods of struct AVL_node; functions avl_insert recursively, left_balance, and right_balance. */ { Error_code result = success; if (sub_root == NULL) { sub_root = new AVL_node(new_data); taller = true; //taller is true for every new node creation } else if (new_data == sub_root->data) {
  • 3. result = duplicate_error; taller = false; } //insert to LST else if (new_data < sub_root->data) { result = avl_insert(sub_root->left, new_data, taller); if (taller == true) switch (sub_root->get_balance()) { case left_higher: //lh before insertion, now unbalanced left_balance(sub_root); taller = false; break; case equal_height: sub_root->set_balance(left_higher); break; case right_higher: sub_root->set_balance(equal_height); taller = false; break; } } //insert to RST else { result = avl_insert(sub_root->right, new_data, taller); if (taller == true) switch (sub_root->get_balance()) { case left_higher: sub_root->set_balance(equal_height); taller = false; break; case equal_height: sub_root->set_balance(right_higher); break; case right_higher: right_balance(sub_root); taller = false;
  • 4. break; } } return result; } template Error_code AVL_tree::avl_delete(Binary_node* &sub_root, const Record &old_data, bool &shorter) { Error_code result = success; Binary_node *temp; if (sub_root == NULL) { result = not_present; shorter = false; } else if (old_data == sub_root->data) { Binary_node *to_delete = sub_root; shorter = true; if (sub_root->right == NULL) { sub_root = sub_root->left; } else if (sub_root->left == NULL) { sub_root = sub_root->right; } else { to_delete = sub_root->right; Binary_node *parent = sub_root; while (to_delete->left != NULL) { parent = to_delete; to_delete = to_delete->left; } sub_root->data = to_delete->data; if (parent == sub_root) { sub_root->right = to_delete->right; }
  • 5. else { parent->left = to_delete->right; } } delete to_delete; } else if (old_data < sub_root->data) { result = avl_delete(sub_root->left, old_data, shorter); if (shorter == true) switch (sub_root->get_balance()) { case left_higher: sub_root->set_balance(equal_height); shorter = true; break; case equal_height: sub_root->set_balance(right_higher); shorter = false; break; case right_higher: temp = sub_root->right; if (temp->get_balance() == equal_height) { shorter = true; } else { shorter = false; } right_balance(sub_root); break; } } else { result = avl_delete(sub_root->right, old_data, shorter); if (shorter == true) switch (sub_root->get_balance()) { case left_higher: temp = sub_root->left;
  • 6. if (temp->get_balance() == equal_height) { shorter = true; } else { shorter = false; } left_balance(sub_root); break; case equal_height: sub_root->set_balance(left_higher); shorter = false; break; case right_higher: sub_root->set_balance(equal_height); shorter = true; break; } } return result; } template void AVL_tree::left_balance(Binary_node* &sub_root) /* Pre: sub_root points to a subtree of an AVL_tree that is doubly unbalanced on the left. Post: The AVL properties have been restored to the subtree. Uses: */ { } template void AVL_tree::right_balance(Binary_node *&sub_root) /*
  • 7. Pre: sub_root points to a subtree of an AVL_tree that is unbalanced on the right. Post: The AVL properties have been restored to the subtree. Uses: Methods of struct AVL_node; functions rotate_right and rotate_left. */ { Binary_node* &right_tree = sub_root->right; // case right_higher: sigle left rotation // O ub --> subroot // // O rh --> right_tree // // O switch (right_tree->get_balance()) { case right_higher: // single left rotation sub_root->set_balance(equal_height); right_tree->set_balance(equal_height); rotate_left(sub_root); //pointer adjustment break; case equal_height: // impossible case cout << "WARNING: If you see this in an insertion, program error is detected in right_balance" << endl; right_tree->set_balance(left_higher); rotate_left(sub_root); break; // case left_higher: double rotation left // O ub --> sub_root // // O lh --> right_tree // / // O three cases --> sub_tree case left_higher: Binary_node *sub_tree = right_tree->left; //set balance of sub_root and right_tree assuming rotation is done switch (sub_tree->get_balance()) {
  • 8. case equal_height: sub_root->set_balance(equal_height); right_tree->set_balance(equal_height); break; case left_higher: sub_root->set_balance(equal_height); right_tree->set_balance(right_higher); break; case right_higher: sub_root->set_balance(left_higher); right_tree->set_balance(equal_height); break; } //set balance of sub_tree after rotation sub_tree->set_balance(equal_height); //perform actual rotation rotate_right(right_tree); rotate_left(sub_root); break; } } //adjustment of pointers template void AVL_tree::rotate_left(Binary_node *&sub_root) /* Pre: sub_root points to a subtree of the AVL_tree. This subtree has a nonempty right subtree. Post: sub_root is reset to point to its former right child, and the former sub_root node is the left child of the new sub_root node. */ { if (sub_root == NULL || sub_root->right == NULL) // impossible cases cout << "WARNING: program error detected in rotate_left" << endl; else { Binary_node *right_tree = sub_root->right;
  • 9. sub_root->right = right_tree->left; right_tree->left = sub_root; sub_root = right_tree; } } template void AVL_tree::rotate_right(Binary_node *&sub_root) /* Pre: sub_root points to a subtree of the AVL_tree. This subtree has a nonempty left subtree. Post: */ { } Solution My Code: /* AVL node */ template class AVLnode { public: T key; int balance; AVLnode *left, *right, *parent; AVLnode(T k, AVLnode *p) : key(k), balance(0), parent(p), left(NULL), right(NULL) {} ~AVLnode() { delete left; delete right; } };
  • 10. /* AVL tree */ template class AVLtree { public: AVLtree(void); ~AVLtree(void); bool insert(T key); void deleteKey(const T key); void printBalance(); private: AVLnode *root; AVLnode* rotateLeft ( AVLnode *a ); AVLnode* rotateRight ( AVLnode *a ); AVLnode* rotateLeftThenRight ( AVLnode *n ); AVLnode* rotateRightThenLeft ( AVLnode *n ); void rebalance ( AVLnode *n ); int height ( AVLnode *n ); void setBalance ( AVLnode *n ); void printBalance ( AVLnode *n ); void clearNode ( AVLnode *n ); }; /* AVL class definition */ template void AVLtree::rebalance(AVLnode *n) { setBalance(n); if (n->balance == -2) { if (height(n->left->left) >= height(n->left->right)) n = rotateRight(n); else n = rotateLeftThenRight(n); } else if (n->balance == 2) {
  • 11. if (height(n->right->right) >= height(n->right->left)) n = rotateLeft(n); else n = rotateRightThenLeft(n); } if (n->parent != NULL) { rebalance(n->parent); } else { root = n; } } template AVLnode* AVLtree::rotateLeft(AVLnode *a) { AVLnode *b = a->right; b->parent = a->parent; a->right = b->left; if (a->right != NULL) a->right->parent = a; b->left = a; a->parent = b; if (b->parent != NULL) { if (b->parent->right == a) { b->parent->right = b; } else { b->parent->left = b; } } setBalance(a);
  • 12. setBalance(b); return b; } template AVLnode* AVLtree::rotateRight(AVLnode *a) { AVLnode *b = a->left; b->parent = a->parent; a->left = b->right; if (a->left != NULL) a->left->parent = a; b->right = a; a->parent = b; if (b->parent != NULL) { if (b->parent->right == a) { b->parent->right = b; } else { b->parent->left = b; } } setBalance(a); setBalance(b); return b; } template AVLnode* AVLtree::rotateLeftThenRight(AVLnode *n) { n->left = rotateLeft(n->left); return rotateRight(n); }
  • 13. template AVLnode* AVLtree::rotateRightThenLeft(AVLnode *n) { n->right = rotateRight(n->right); return rotateLeft(n); } template int AVLtree::height(AVLnode *n) { if (n == NULL) return -1; return 1 + std::max(height(n->left), height(n->right)); } template void AVLtree::setBalance(AVLnode *n) { n->balance = height(n->right) - height(n->left); } template void AVLtree::printBalance(AVLnode *n) { if (n != NULL) { printBalance(n->left); std::cout << n->balance << " "; printBalance(n->right); } } template AVLtree::AVLtree(void) : root(NULL) {} template AVLtree::~AVLtree(void) { delete root; } template
  • 14. bool AVLtree::insert(T key) { if (root == NULL) { root = new AVLnode(key, NULL); } else { AVLnode *n = root, *parent; while (true) { if (n->key == key) return false; parent = n; bool goLeft = n->key > key; n = goLeft ? n->left : n->right; if (n == NULL) { if (goLeft) { parent->left = new AVLnode(key, parent); } else { parent->right = new AVLnode(key, parent); } rebalance(parent); break; } } } return true; } template
  • 15. void AVLtree::deleteKey(const T delKey) { if (root == NULL) return; AVLnode *n = root, *parent = root, *delNode = NULL, *child = root; while (child != NULL) { parent = n; n = child; child = delKey >= n->key ? n->right : n->left; if (delKey == n->key) delNode = n; } if (delNode != NULL) { delNode->key = n->key; child = n->left != NULL ? n->left : n->right; if (root->key == delKey) { root = child; } else { if(parent->left == n){ parent->left = child; } else { parent->right = child; } rebalance(parent); } } }