I am writing a program in C++ that will implement an AVL tree. the first part of
ID: 3725084 • Letter: I
Question
I am writing a program in C++ that will implement an AVL tree. the first part of the insertion should work where a node gets inserted like a normal BST node, but after that, I'm not so sure I did this correctly. I don't think my while loop in the insertion is working. I need to be able to check if the balence factor is correct starting from the leaf node to the root node which is why I have the while loop. here is the code:
BSTNode::BSTNode(int key) :
key_(key),
parent_(std::weak_ptr<BSTNode>()),
left_(nullptr),
right_(nullptr) {
}
BSTNode::BSTNode(int key, std::weak_ptr<BSTNode> parent) :
key_(key),
parent_(parent),
left_(nullptr),
right_(nullptr) {
}
bool BSTNode::IsLeaf() const {
return left_ == nullptr && right_ == nullptr;
}
bool BSTNode::HasLeftChild() const {
return left_ != nullptr;
}
bool BSTNode::HasRightChild() const {
return right_ != nullptr;
}
void BST::Balance(){
if (balance > 1 && key < node->left_->key)
return rightRotate(node);
if (balance < -1 && key > node->right_->key)
return leftRotate(node);
if (balance > 1 && key > node->left_->key)
{
node->left = leftRotate(node->left_);
return rightRotate(node);
}
if (balance < -1 && key < node->right_->key)
{
node->right = rightRotate(node->right_);
return leftRotate(node);
}
}
int BSTNode::rightRotate(std::shared_ptr<BSTNode> y)
{
weak_ptr<BSTNode> parent = y->parent;
shared_ptr<BSTNode> x = y->left_;
shared_ptr<BSTNode> t3 = y->right_;
shared_ptr<BSTNode> t1 = x->left;
shared_ptr<BSTNode> t2 = x->right;
// Perform rotation
x->right_ = y;
y->left_ = t2;
t2.parent=y;
y->parent=x;
x->parent= parent;
if(parent->left_-> == x)
parent->left = x;
if(parent->right_->key == x->key)
parent->right = x;
// 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;
}
int BSTNode::leftRotate(std::shared_ptr<BSTNode> x)
{
weak_ptr<BSTNode> parent = x->parent;
shared_ptr<BSTNode> t1 = x->left_;
shared_ptr<BSTNode> y = x->right_;
shared_ptr<BSTNode> t2 = y->left;
shared_ptr<BSTNode> t3 = y->right;
// Perform rotation
y->left_ = x;
x->right_ = t2;
t2->parent=x;
x->parent=y;
y->parent= parent;
//determine if left child or right child
if(parent->left_->key == y->key)
parent->left_ = y;
else
parent->right = y;
// 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;
}
void BSTNode::DeleteChild(std::shared_ptr<BSTNode> v) {
if (left_ == v) {
left_ = nullptr;
} else if (right_ == v) {
right_ = nullptr;
} else {
std::cerr << "BSTNode::DeleteChild Error: non-child passed as argument ";
exit(EXIT_FAILURE);
}
}
void BSTNode::ReplaceChild(std::shared_ptr<BSTNode> v, std::shared_ptr<BSTNode> u) {
if (left_ == u || right_ == u) {
std::cerr << "BSTNode::ReplaceChild Error: child passed as replacement ";
}
if (left_ == v) {
left_ = u;
u->parent_ = v->parent_;
} else if (right_ == v) {
right_ = u;
u->parent_ = v->parent_;
} else {
std::cerr << "BSTNode::ReplaceChild Error: non-child passed as argument ";
exit(EXIT_FAILURE);
}
}
BST::BST() : root_(nullptr), size_(0) {}
int BST::getBalance(std::shared_prt<BSTNode> N){
if (N == NULL)
return 0;
return height(N->left) - height(N->right);
}
int BST::height(std::shared_ptr<BSTNODE> N){
int t;
if (N == NULL)
return -1;
else
{
t = p->height;
return t;
}
}
void BST::Insert(int key) {
if (root_ == nullptr) {
root_ = std::make_shared<BSTNode>(key);
size_++;
return;
}
std::shared_ptr<BSTNode> currentNode = root_, lastNode = nullptr;
while (currentNode != nullptr) {
lastNode = currentNode;
currentNode = (key < currentNode->key_) ?
currentNode->left_ : currentNode->right_;
}
if (key < lastNode->key_) {
lastNode->left_ = std::make_shared<BSTNode>(key, lastNode);
}
else {
lastNode->right_ = std::make_shared<BSTNode>(key, lastNode);
}
size_++;
//Starting from w, travel up and find the first unbalanced node.
// Let z be the first unbalanced node, y be the child of z that comes on the path
//from w to z and x be the grandchild of z that comes on the path from w to z.
int balance = getBalance(lastNode);
if(balance!=-1 || balance!=1 || balance!=0){
Balance(lastNode);
}
bool BST::Delete(int key) {
std::shared_ptr<BSTNode> currentNode = root_;
while (currentNode != nullptr) {
if (currentNode->key_ == key) {
if (currentNode->IsLeaf()) {
DeleteLeaf(currentNode);
} else if (currentNode->left_ == nullptr) {
assert(currentNode->right_ != nullptr);
std::shared_ptr<BSTNode> parent = currentNode->parent_.lock();
parent->ReplaceChild(currentNode, currentNode->right_);
size_--; assert(size_ >= 0);
} else if (currentNode->right_ == nullptr) {
assert(currentNode->left_ != nullptr);
std::shared_ptr<BSTNode> parent = currentNode->parent_.lock();
parent->ReplaceChild(currentNode, currentNode->left_);
size_--; assert(size_ >= 0);
} else {
currentNode->key_ = DeleteMin(currentNode);
}
}
currentNode = (key < currentNode->key_) ?
currentNode->left_ : currentNode->right_;
}
return false;
while(lastNode!=root_){
balance=getBalance(lastNode);
Balance(lastNode);
}
}
Explanation / Answer
#include<stdio.h>
#include<stdlib.h>
// An AVL tree node
struct Node
{
int key;
struct Node *left;
struct Node *right;
int height;
};
// A utility function to get maximum of two integers
int max(int a, int b);
// 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
int max(int 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(int 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 getBalance(struct Node *N)
{
if (N == NULL)
return 0;
return height(N->left) - height(N->right);
}
// Recursive function to insert key in subtree rooted
// with node and returns new root of subtree.
struct Node* insert(struct Node* node, int key)
{
/* 1. Perform the normal BST insertion */
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 are not allowed in BST
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 = getBalance(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;
}
// A utility function to print preorder traversal
// of the tree.
// The function also prints height of every node
void preOrder(struct Node *root)
{
if(root != NULL)
{
printf("%d ", root->key);
preOrder(root->left);
preOrder(root->right);
}
}
/* Drier program to test above function*/
int main()
{
struct Node *root = NULL;
/* Constructing tree given in the above figure */
root = insert(root, 10);
root = insert(root, 20);
root = insert(root, 30);
root = insert(root, 40);
root = insert(root, 50);
root = insert(root, 25);
/* The constructed AVL Tree would be
30
/
20 40
/
10 25 50
*/
printf("Preorder traversal of the constructed AVL"
" tree is ");
preOrder(root);
return 0;
}
Run on IDE
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.