Assignment9
Assignment9
Lab Assignment - 9
Implement AVL tree insertion and deletion.
Code :
#include <iostream>
#include <algorithm>
// 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 x;
}
// 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 y;
}
// No rotation needed
return node;
}
// Function to nd the node with minimum key value in a subtree rooted with given node
Node* minValueNode(Node* node) {
Node* current = node;
return current;
}
// No child case
if (temp == nullptr) {
temp = root;
root = nullptr;
} else // One child case
*root = *temp; // Copy the contents of the non-empty child
delete temp;
} else {
fi
fi
// Node with two children: Get the inorder successor (smallest in the right subtree)
Node* temp = minValueNode(root->right);
return root;
}
int main() {
Node* root = nullptr;
// Inserting nodes
root = insertNode(root, 10);
root = insertNode(root, 20);
root = insertNode(root, 30);
root = insertNode(root, 40);
root = insertNode(root, 50);
root = insertNode(root, 25);
// Deleting nodes
root = deleteNode(root, 20);
cout << "Inorder traversal after deleting 20: ";
inorderTraversal(root);
cout << endl;
return 0;
}
Output :