Avl Tree Implementation 307
Avl Tree Implementation 307
ROLL NO 307
USN :01FE21BEC110
C DIV
Problem Statement:
Consider a real-time stock market data system where you
need to keep track of the current stock prices and perform
efficient searches for finding the highest or lowest priced
stocks. Implement an AVL tree to store the stock prices, with
each node representing a stock and its associated price. The
tree should be dynamically updated as prices change, and you
should be able to quickly retrieve the highest or lowest priced
stock by traversing the appropriate subtree.
CODE:
#include <stdio.h>
#include <stdlib.h>
// Update heights
y->height = max(getHeight(y->left), getHeight(y->right)) + 1;
x->height = max(getHeight(x->left), getHeight(x->right)) + 1;
return x;
}
// Update heights
x->height = max(getHeight(x->left), getHeight(x->right)) + 1;
y->height = max(getHeight(y->left), getHeight(y->right)) + 1;
return y;
}
return node;
}
// Function to find the node with the lowest price (leftmost node)
struct Node* findLowestPrice(struct Node* node) {
if (node == NULL || node->left == NULL)
return node;
return findLowestPrice(node->left);
}
// Function to find the node with the highest price (rightmost node)
struct Node* findHighestPrice(struct Node* node) {
if (node == NULL || node->right == NULL)
return node;
return findHighestPrice(node->right);
}
// Function to find and delete the node with the given price
struct Node* deleteNode(struct Node* root, float price) {
if (root == NULL)
return root;
// No child case
if (temp == NULL) {
temp = root;
root = NULL;
} else // One child case
*root = *temp; // Copy the contents of the non-empty child
free(temp);
} else {
// Case 2: Two children
struct Node* successor = findLowestPrice(root->right); // Find
the inorder successor (smallest in the right subtree)
return root;
}
int main() {
struct Node* root = NULL;
int stock;
float price;
int numStocks;
if (lowestStock != NULL)
printf("\nLowest priced stock: Stock %d, Price: %.2f\n",
lowestStock->stock, lowestStock->price);
if (highestStock != NULL)
printf("Highest priced stock: Stock %d, Price: %.2f\n",
highestStock->stock, highestStock->price);
// Deleting a node with a specific price
float deletePrice;
printf("\nEnter the price of the stock to delete: ");
scanf("%f", &deletePrice);
root = deleteNode(root, deletePrice);
return 0;
}
OUTPUT SCREEN SHOT: