Binary tree nodes with index - c++

I need to make optimized search for vector using binary search tree.
for example I have vector<int> numbers where I store {5,4,3,2,1}
then I copy those 1,2,3,4,5 to binary tree and need to return index where it is stored in vector.
For example, search(4) will have to return 1 because numbers[1] = 4
I've tried giving nodes index but they don't match in the end
Is there a better solution or how do I correctly give index to tree nodes
struct node {
int data;
int index;
node* left;
node* right;
};
node* insert(int x, node* t) {
if(t == NULL) {
t = new node;
t->data = x;
t->index = 0;
t->left = t->right = NULL;
}
else if(x < t->data) {
t->left = insert(x, t->left);
t->index += 1;
}
else if(x > t->data) {
t->right = insert(x, t->right);
t->index += 0;
}
return t;
}
node* find(node* t, int x) {
if(t == NULL)
return NULL;
else if(x < t->data) {
return find(t->left, x);
}
else if(x > t->data) {
return find(t->right, x);
}
else
return t;
}
int main() {
BST t;
vector<int> storage;
for ( int i =0; i< 10; i++) {
storage.push_back(rand()%100 +1);
t.insert(storage[i]);
}
t.display();
t.search(15);
}

node* insert(int x, node* t, int index)
{
if(t == NULL)
{
t = new node;
t->data = x;
t->index = index;
t->left = t->right = NULL;
}
else if(x < t->data)
{
t->left = insert(x, t->left, index);
}
else if(x > t->data)
{
t->right = insert(x, t->right, index);
}
return t;
}

Related

Why is my Ranked Binary search tree implementation is so slow?

So I wrote a Ranked self-balancing Binary Search Tree instead of using std::set. I was expecting it to work faster for getting rank of elements, but it seems to take more time than using std::set and iterating through to find rank. Is there any way to speed it up?
#include<bits/stdc++.h>
struct treeNode{
int data;
int leftsize; //for finding rank
int height; //for balancing during insertions and deletions
treeNode* left;
treeNode* right;
treeNode()
:data(NAN), leftsize(0), left(nullptr), right(nullptr){}
treeNode(int val, int lsize, int ht)
:data(val), leftsize(lsize), height(ht), left(nullptr), right(nullptr){}
};
int height(treeNode* node)
{
if(node == nullptr)
return 0;
return node->height;
}
int getBalance(treeNode* node)
{
if(node==nullptr)
return 0;
return height(node->left) - height(node->right);
}
int parseLeftSub(treeNode* node)
{
if(node == nullptr)
return 0;
int cnt = 1;
cnt += parseLeftSub(node->left);
cnt += parseLeftSub(node->right);
return cnt;
}
void printNode(treeNode* node)
{
if(node == nullptr)
return;
printNode(node->left);
std::cout << node->data << " " << node->leftsize << std::endl;
printNode(node->right);
}
treeNode* createNode(int val)
{
treeNode* node = new treeNode(val, 1, 1);
return node;
}
treeNode* createTree(std::vector<int>& a, int start, int end)
{
if(start>end)
return nullptr;
int mid = (start + end)/2;
treeNode* node = createNode(a[mid]);
node->left = createTree(a, start, mid-1);
node->right = createTree(a, mid+1, end);
node->leftsize += parseLeftSub(node->left);
return node;
}
treeNode* rightRotate(treeNode* y)
{
treeNode* x = y->left;
treeNode* T2 = x->right;
// Perform rotation
x->right = y;
y->left = T2;
// Update heights
y->height = std::max(height(y->left),
height(y->right)) + 1;
x->height = std::max(height(x->left),
height(x->right)) + 1;
// Return new root
y->leftsize = parseLeftSub(y->left) + 1;
return x;
}
treeNode* leftRotate(treeNode* x)
{
treeNode* y = x->right;
treeNode* T2 = y->left;
// Perform rotation
y->left = x;
x->right = T2;
// Update heights
x->height = std::max(height(x->left),
height(x->right)) + 1;
y->height = std::max(height(y->left),
height(y->right)) + 1;
// Return new root
y->leftsize = parseLeftSub(y->left) + 1;
return y;
}
treeNode* insertNode(int val, treeNode* node)
{
if(node == nullptr)
return createNode(val);
if(val < node->data)
node->left = insertNode(val, node->left);
else if(val > node->data)
node->right = insertNode(val, node->right);
else
return node;
node->height = 1 + std::max(height(node->left), height(node->right));
node->leftsize = parseLeftSub(node->left) + 1;
int balance = getBalance(node);
if(balance > 1 && val < node->left->data)
return rightRotate(node);
else if(balance < -1 && val > node->right->data)
return leftRotate(node);
else if(balance > 1 && val > node->left->data)
{
node->left = leftRotate(node->left);
return rightRotate(node);
}
else if(balance < -1 && val < node->right->data)
{
node->right = rightRotate(node->right);
return leftRotate(node);
}
return node;
}
treeNode* searchNode(int val, treeNode* node)
{
if(node == nullptr)
return nullptr;
treeNode* foundNode = nullptr;
if(val == node->data)
return node;
else if(val < node->data)
foundNode = searchNode(val, node->left);
else
foundNode = searchNode(val, node->right);
return foundNode;
}
treeNode* findLowerBound(int val, treeNode* node)
{
if(node == nullptr)
return nullptr;
if(val == node->data)
return node;
else if(val>node->data)
{
return(findLowerBound(val, node->right));
}
treeNode* temp = findLowerBound(val, node->left);
if(temp != nullptr && temp->data >= val)
return temp;
else
return node;
}
treeNode* findUpperBound(int val, treeNode* node)
{
if(node == nullptr)
return nullptr;
if(val == node->data)
return node;
else if(val<node->data)
{
return(findUpperBound(val, node->left));
}
treeNode* temp = findUpperBound(val, node->right);
if(temp != nullptr && temp->data <= val)
return temp;
else
return node;
}
treeNode* findMinNode(treeNode* node)
{
if(node->left == nullptr)
return node;
return (findMinNode(node->left));
}
treeNode* deleteNode(int val, treeNode*& node)
{
if(node == nullptr)
return nullptr;
if(node->data > val)
node->left = deleteNode(val, node->left);
else if(node->data < val)
node->right = deleteNode(val, node->right);
else
{
if(node->left==nullptr && node->right==nullptr)
{
delete node;
node = nullptr;
}
else if(node->left==nullptr)
{
treeNode* temp = node;
node = node->right;
delete temp;
}
else if(node->right==nullptr)
{
treeNode* temp = node;
node = node->left;
delete temp;
}
else
{
treeNode* temp = findMinNode(node->right);
node->data = temp->data;
node->right = deleteNode(temp->data, node->right);
}
}
if (node == NULL)
return node;
node->leftsize = parseLeftSub(node->left) + 1;
node->height = 1 + std::max(height(node->left),
height(node->right));
int balance = getBalance(node);
if (balance > 1 &&
getBalance(node->left) >= 0)
return rightRotate(node);
if (balance > 1 &&
getBalance(node->left) < 0)
{
node->left = leftRotate(node->left);
return rightRotate(node);
}
if (balance < -1 &&
getBalance(node->right) <= 0)
return leftRotate(node);
if (balance < -1 &&
getBalance(node->right) > 0)
{
node->right = rightRotate(node->right);
return leftRotate(node);
}
return node;
}
int findRank(int val, treeNode* node)
{
int rank = node->leftsize;
if(node==nullptr)
{
return -1;
}
if(val<node->data)
{
rank -= node->leftsize;
rank += findRank(val, node->left);
}
else if(val>node->data)
{
rank += findRank(val, node->right);
}
return rank;
}
I know its quite a lot. Also can any other stl containers be used to find rank, insert and delete efficiently

problems in implementation of avl

I am trying to insert 0 through 11 into avl and then delete 4, 5, 6 in that order. I am getting sigserv error while deleting 6 in rr_rotation function. This is the first time I am implementing avl and I am new to programming. Where am I going wrong? I added a few comments for my own understanding and to track where the error has occurred. Here is my code:
#include<bits/stdc++.h>
using namespace std;
#define pow2(n) (1 << (n))
struct avl_node {
int data;
//int size;
struct avl_node *left;
struct avl_node *right;
}*root;
class avlTree {
public:
int height(avl_node *);
int diff(avl_node *);
avl_node *rr_rotation(avl_node *);
avl_node *ll_rotation(avl_node *);
avl_node *lr_rotation(avl_node *);
avl_node *rl_rotation(avl_node *);
avl_node* balance(avl_node *);
avl_node* insert(avl_node *, int);
int getBalance(avl_node*);
int getSize(avl_node*);
avl_node* minValueNode(avl_node*);
avl_node* del(avl_node *, int);
void inorder(avl_node *);
void preorder(avl_node *);
int kthsmallest(avl_node*, int);
avlTree() {
root = NULL;
}
};
int avlTree::height(avl_node *temp) {
int h = 0;
if (temp != NULL) {
int l_height = height(temp->left);
int r_height = height(temp->right);
int max_height = max(l_height, r_height);
h = max_height + 1;
}
return h;
}
int avlTree::diff(avl_node *temp) {
int l_height = height(temp->left);
int r_height = height(temp->right);
int b_factor = l_height - r_height;
return b_factor;
}
avl_node *avlTree::rr_rotation(avl_node *parent) {
avl_node *temp;
cout<<"inside rr rotation"<<endl;
cout<<"parent = "<<parent->data<<endl;
temp = parent->right;
if(temp == NULL)
cout<<"yes null 2"<<endl;
//cout<<"parent->right "<<temp->data<<endl;
parent->right = temp->left;
temp->left = parent;
cout<<"temp->left->data "<<temp->left->data<<endl;
return temp;
}
avl_node *avlTree::ll_rotation(avl_node *parent) {
avl_node *temp;
//cout<<"inside ll rotation"<<endl;
//cout<<"parent = "<<parent->data<<endl;
temp = parent->left;
parent->left = temp->right;
temp->right = parent;
return temp;
}
avl_node *avlTree::lr_rotation(avl_node *parent) {
avl_node *temp;
cout<<"inside lr rotation"<<endl;
cout<<"parent = "<<parent->data<<endl;
temp = parent->left;
parent->left = rr_rotation(temp);
return ll_rotation(parent);
}
avl_node *avlTree::rl_rotation(avl_node *parent) {
avl_node *temp;
cout<<"inside rl rotation"<<endl;
cout<<"parent = "<<parent->data<<endl;
temp = parent->right;
parent->right = ll_rotation(temp);
return rr_rotation(parent);
}
avl_node *avlTree::balance(avl_node *temp) {
int bal_factor = diff(temp);
if (bal_factor > 1) {
if (diff(temp->left) > 0)
temp = ll_rotation(temp);
else
temp = lr_rotation(temp);
} else if (bal_factor < -1) {
if (diff(temp->right) > 0)
temp = rl_rotation(temp);
else
temp = rr_rotation(temp);
}
return temp;
}
avl_node *avlTree::insert(avl_node *root, int value) {
//cout<<"Inside insert for val = "<<value<<endl;
if (root == NULL) {
root = new avl_node;
root->data = value;
root->left = NULL;
root->right = NULL;
return root;
} else if (value < root->data) {
root->left = insert(root->left, value);
root = balance(root);
} else if (value >= root->data) {
root->right = insert(root->right, value);
root = balance(root);
}
return root;
}
avl_node* avlTree::minValueNode(avl_node* node) {
avl_node* current = node;
while (current->left != NULL)
current = current->left;
return current;
}
int avlTree::getBalance(avl_node* N) {
if (N == NULL)
return 0;
return height(N->left) - height(N->right);
}
avl_node* avlTree::del(avl_node *root, int value) {
cout<<"del for val = "<<value<<endl;
if (root == NULL){
cout<<"root is null here\n";
return root;
}
// If the key to be deleted is smaller than the
// root's key, then it lies in left subtree
if (value < root->data)
root->left = del(root->left, value);
// If the key to be deleted is greater than the
// root's key, then it lies in right subtree
else if (value > root->data)
root->right = del(root->right, value);
// if key is same as root's key, then This is
// the node to be deleted
else {
// node with only one child or no child
if ((root->left == NULL) || (root->right == NULL)) {
avl_node* temp = root->left ? root->left : root->right;
// No child case
if (temp == NULL) {
temp = root;
root = NULL;
cout<<"Root set to null\n";
}
else{
// One child case
cout<<temp->data<<" copied to root "<<root->data<<"\n";
*root = *temp;
// Copy the contents of
// the non-empty child
}
free(temp);
} else {
// node with two children: Get the inorder
// successor (smallest in the right subtree)
avl_node* temp = minValueNode(root->right);
// Copy the inorder successor's data to this node
root->data = temp->data;
// Delete the inorder successor
root->right = del(root->right, temp->data);
}
} // If the tree had only one node then return
if (root == NULL)
return root;
// STEP 2: UPDATE HEIGHT OF THE CURRENT NODE
//root->height = 1 + max(height(root->left),height(root->right));
// STEP 3: GET THE BALANCE FACTOR OF THIS NODE (to
// check whether this node became unbalanced)
int balance = getBalance(root);
cout<<"balance = "<<balance<<" for root "<<root->data<<endl;
if(root->right == NULL)
cout<<"yes null"<<endl;
// If this node becomes unbalanced, then there are 4 cases// Left Left Case
if (balance > 1 && getBalance(root->left) >= 0){
cout<<"balance1 = "<<getBalance(root->left)<<" for root "<<root->left->data<<endl;
avl_node* t = rr_rotation(root);
//root = rr_rotation(root);
cout<<"Root of the modified sub-tree is "<<t->data<<endl;
return t;
//rr_rotation(root);
}
// Left Right Case
if (balance > 1 && getBalance(root->left) < 0) {
cout<<"balance2 = "<<getBalance(root->left)<<" for root "<<root->left->data<<endl;
cout<<"prev root "<<root->left->data<<endl;
//root->left = ll_rotation(root->left);
root = lr_rotation(root);
cout<<"new root "<<root->data<<endl;
//return rr_rotation(root);
return root;
} // Right Right Case
if (balance < -1 && getBalance(root->right) <= 0){
cout<<"balance3 = "<<getBalance(root->right)<<" for root "<<root->right->data<<endl;
avl_node* t = rr_rotation(root);
cout<<"Root of the modified sub-tree is "<<t->data<<endl;
return t;
//return ll_rotation(root);
}
// Right Left Case
if (balance < -1 && getBalance(root->right) > 0) {
cout<<"balance4 = "<<getBalance(root->right)<<" for root "<<root->right->data<<endl;
//root->right = rr_rotation(root->right);
//return ll_rotation(root);
return rl_rotation(root);
}
return root;
}
void avlTree::inorder(avl_node *tree) {
if (tree == NULL)
return;
inorder(tree->left);
cout << tree->data << " ";
inorder(tree->right);
}
void avlTree::preorder(avl_node *tree) {
if (tree == NULL)
return;
cout << tree->data << " ";
preorder(tree->left);
preorder(tree->right);
}
int avlTree::getSize(avl_node* N){
if(N == NULL)
return 0;
return (getSize(N->left) + 1 + getSize(N->right));
}
int avlTree::kthsmallest(avl_node* N, int k){
int r = getSize(N->left) + 1;
if(k == r)
return N->data;
if(k < r)
return kthsmallest(N->left,k);
if(k > r)
return kthsmallest(N->right,k-r);
return -1;
}
int main(void) {
int n, i, x;
char s;
avlTree tree; for(i=0;i<12;i++){
root = tree.insert(root,i);
tree.preorder(root);
cout<<endl;
}
for(i=4;i<=6;i++){
root = tree.del(root,6);
tree.preorder(root);
cout<<endl;
}
return 0;
}

AVL Tree node deletion

I was trying to implement AVL Tree in C++, I Implemented key insertion without much problem but while trying to delete a node I ran into use after free bug. I tried to debug with gdb but I was unable to find out the problem, Here's the full code.
#include <iostream>
#include <algorithm>
using namespace std;
class Node;
class AVLTree;
typedef Node* node_ptr;
class Node {
int key;
int height;
node_ptr left;
node_ptr right;
void fix_height() {
int hR, hL = 0;
if (left) hL = left->height;
if (right) hR = right->height;
height = max(hL, hR) + 1;
}
int balance_factor() {
if (left && right)
return left->height - right->height;
if (left && !right)
return left->height;
if (right && !left)
return -right->height;
return 0;
}
public:
Node(int key) :key(key), left(nullptr), right(nullptr),height(1){}
friend class AVLTree;
};
class AVLTree {
node_ptr mRoot;
node_ptr insert(node_ptr node, int key) {
if (!node) return new Node(key);
if (node->key > key) node->left = insert(node->left, key);
else node->right = insert(node->right, key);
return balance(node);
}
node_ptr left_rotate(node_ptr X) {
node_ptr Y = X->right;
X->right = Y->left;
Y->left = X;
X->fix_height();
Y->fix_height();
return Y;
}
node_ptr right_rotate(node_ptr Y) {
node_ptr X = Y->left;
Y->left = X->right;
X->right = Y;
X->fix_height();
Y->fix_height();
return X;
}
node_ptr balance(node_ptr node) {
node->fix_height();
int b_factor = node->balance_factor();
if (b_factor == 2) {
if (node->left->balance_factor() < 0) {
node->left = left_rotate(node->left);
}
return right_rotate(node);
}
else if (b_factor == -2) {
if (node->right->balance_factor() > 0) {
node->right = right_rotate(node->right);
}
return left_rotate(node);
}
return node;
}
node_ptr find_min(node_ptr node) {
if (!node) return nullptr;
if (!node->left) return node;
else return
find_min(node->left);
}
node_ptr remove_min(node_ptr node) {
if (!node->left)
return node->right;
node->left = remove_min(node->left);
return balance(node);
}
node_ptr remove(node_ptr node, int key) {
if (!node) return nullptr;
if (node->key > key)
node->left = remove(node->left, key);
else if (node->key < key)
node->right = remove(node->right, key);
else {
node_ptr L = node->left;
node_ptr R = node->right;
delete node;
if (!R) return L;
node_ptr min = find_min(node->right);
min->right = remove_min(R);
min->left = L;
return balance(min);
}
return balance(node);
}
void print_inorder(node_ptr node) {
if (node) {
print_inorder(node->left);
cout << node->key << " ";
print_inorder(node->right);
}
}
public:
AVLTree() :mRoot(nullptr) {}
void insert(int key) {
mRoot = insert(mRoot, key);
}
void remove(int key) {
mRoot = remove(mRoot, key);
}
void print_inorder() {
cout << endl;
print_inorder(mRoot);
cout << endl;
}
};
int main()
{
AVLTree mtree;
for (int i = 0; i < 3; ++i) {
mtree.insert(i);
}
mtree.remove(0);
mtree.remove(1);
mtree.remove(2);
mtree.print_inorder();
return 0;
}
So, In remove_min(), I am using the same logic as a binary search tree. If sub-tree has a right child, minimum element from that right subtree is returned, and replaced with the target node, If not then just pointer to left subtree is returned and as function returns it balances the disturbed nodes. But somehow deleted node is getting referenced and I am getting segmentation fault. I cannot figure out how. Can someone help ?

A count function that counts the leaf nodes of a height balanced tree

I'm writing a function that counts the leaf nodes of a height balanced tree using struct and pointers. The function takes 3 arguments: the tree, pointer to an array and the maximum depth of the tree. The length of the array is the maximum depth. When function is called the array is initialized to zero. The function recursively follows the tree structure,
keeping track of the depth, and increments the right counter whenever it reaches a leaf. The function does not follow any pointer deeper than maxdepth. The function returns 0 if there was no leaf at depth greater than maxdepth, and 1 if there was some pointer togreater depth. What is wrong with my code. Thanks.
typedef int object;
typedef int key;
typedef struct tree_struct { key key;
struct tree_struct *left;
struct tree_struct *right;
int height;
} tree_n;
int count_d (tree_n *tr, int *count, int mdepth)
{
tree_n *tmp;
int i;
if (*(count + 0) == NULL){
for (i =0; i<mdepth; i++){
*(count + i) = 0;
}
}
while (medepth != 0)
{
if (tr == NULL) return;
else if ( tree-> left == NULL || tree->right == NULL){
return (0);
}
else {
tmp = tr;
*(count + 0) = 1;
int c = 1;
while(tmp->left != NULL && tmp->right != NULL){
if(tmp-> left){
*(count + c) = 2*c;
tmp = tmp->left;
return count_d(tmp, count , mdepth);
}
else if(tmp->right){
*(count + c + 1) = 2*c + 1;
tmp = tmp->right;
return count_d(tmp,count, mdepth);
}
c++;
mpth--;
}
}
}
What is wrong with my code
One thing I noticed is that you are missing return in the recursive calls.
return count_d(tmp, count , mdepth);
// ^^^ Missing
There are two such calls. Make sure to add return to both of them.
Disclaimer: Fixing this may not fix all your problems.
Correct Function To Insert,Count All Nodes and Count Leaf Nodes
#pragma once
typedef int itemtype;
#include<iostream>
typedef int itemtype;
#include<iostream>
#include<conio.h>
#include<string>
using namespace std;
class Node
{
public:
Node* left;
Node* right;
itemtype data;
};
class BT
{
private:
int count = 0;
Node* root;
void insert(itemtype d, Node* temp);//Override Function
public:
BT();//Constructor
bool isEmpty();
Node* newNode(itemtype d);
Node* getroot();
void insert(itemtype d);//Function to call in main
int countLeafNodes(Node * temp);
int countAllNodes();//to count all nodes
}
BT::BT()//constructor
{
root = NULL;
}
bool BT::isEmpty()
{
if (root == NULL)
return true;
else
return false;
}
Node* BT::newNode(itemtype d)
{
Node* n = new Node;
n->left = NULL;
n->data = d;
n->right = NULL;
return n;
}
void BT::insert(itemtype d)//Function to call in main
{
if (isEmpty())
{
Node* temp = newNode(d);
root = temp;
}
else
{
Node* temp = root;
insert(d, temp);
}
count++;//to count number of inserted nodes
}
void BT::insert(itemtype d, Node* temp)//Private Function which is overrided
{
if (d <= temp->data)
{
if (temp->left == NULL)
{
Node* n = newNode(d);
temp->left = n;
}
else
{
temp = temp->left;
insert(d, temp);
}
}
else
{
if (temp->right == NULL)
{
temp->right = newNode(d);
}
else
{
temp = temp->right;
insert(d, temp);
}
}
}
int BT::countAllNodes()
{ return count; }
int BT::countLeafNodes(Node* temp)
{
int leaf = 0;
if (temp == NULL)
return leaf;
if (temp->left == NULL && temp->right == NULL)
return ++leaf;
else
{
leaf = countLeafNodes(temp->left) + countLeafNodes(temp->right);
return leaf;
}
}
void main()
{
BT t;
t.insert(7);
t.insert(2);
t.insert(3);
t.insert(15);
t.insert(11);
t.insert(17);
t.insert(18);
cout<<"Total Number Of Nodes:" <<t.countAllNodes() <<endl;
cout << "Leaf Nodes:" << t.countLeafNodes(t.getroot()) << endl;
_getch();
}
Output:
Ouput

AVL Trees and Doubly Linked Lists

so, I am really new to programming, and I am taking a c++ class right now, in which I need to write and implement and AVL Tree, using a Doubly Linked lists to print off the contents of my tree, level by level. The teacher is really picky, so we can't use any containers from the standard libraries. My Doubly Linked list should be working fine, because I used it on a previous project, but I am getting an error when trying to combine it with the AVL Tree. I know my code probably has A LOT of things that need to be modified, but one step at a time. I am getting the following error, so I was wondering if you guys could help me figure out how to fix it. Also, if you have any suggestions on how to better my code, I would appreciate it.
In instantiation of ‘void AVLTreeSet::print(std::ofstream&) [with ItemType = std::basic_string; std::ofstream = std::basic_ofstream]’:
Lab6/main.cpp:80:20: required from here
Lab6/AVLTreeSet.h:152:49: error: cannot convert ‘LinkedList >::AVLNode*>::Node*’ to ‘AVLTreeSet >::AVLNode*’ in initialization
AVLNode* n = MyList.remove(i);
This is my AVLTree.h:
#pragma once
#include <fstream>
#include "LinkedList.h"
using namespace std;
template <typename ItemType>
class AVLTreeSet {
struct AVLNode {
ItemType item;
int height;
AVLNode* left;
AVLNode* right;
AVLNode(const ItemType& _item, AVLNode* _left = NULL, AVLNode* _right = NULL, int _height = 0) :
item(_item), left(_left), right(_right), height(_height) {}
};
AVLNode* root;
int size = 0;
public:
void RemoveBelowRoot(AVLNode *& n, const ItemType& item)
{
if (n == NULL)
{
return;
}
else if(item < n->item)
{
RemoveBelowRoot(n->left, item);
}
else if(item > n->item)
{
RemoveBelowRoot(n->right, item);
}
else if(n->left == NULL)
{
n = n->right;
}
else if (n->right == NULL)
{
n = n->left;
}
else
{
n = findMin(n->right);
RemoveBelowRoot(n->right, n->item);
}
balance(n);
size--;
// update height of nodes on this path
}
AVLNode * findMin(AVLNode* n)
{
if (n == NULL)
{
return n;
}
else if (n->left->item < n->item)
{
findMin(n->left);
}
else if(n->left->item > n->item)
{
findMin(n->right);
}
return n;
}
void remove(const ItemType& item) {
RemoveBelowRoot(root, item);
}
bool find(const ItemType& item) {
if (findBelowRoot(root, item))
{
return true;
}
return false;
}
bool findBelowRoot(AVLNode * n, const ItemType& data)
{
if (n->item == data)
{
return true;
}
else if (data > n->item)
{
findBelowRoot(n->right, data);
}
else if (data < n->item)
{
findBelowRoot(n->left, data);
}
}
void clear()
{
while (getHeight(root) != 0)
{
// remove
}
}
void addBelowRoot(AVLNode *& n, const ItemType& item)
{
if (n == NULL)
{
n = new AVLNode(item);
size++;
}
else if (item < n->item)
{
addBelowRoot(n->left, item);
}
else if(item > n->item)
{
addBelowRoot(n->right, item);
}
}
void add(const ItemType& item) {
addBelowRoot(root, item);
}
void print (ofstream& out)
{
if (root == NULL)
{
return;
}
else {
LinkedList<AVLNode *> MyList;
MyList.insert(0, root); // add root to Q
while (MyList.getSize() != 0) // While Q is not empty
//(figure out how many items are in that level)(levelsize = Q.size();)
{
for (auto i = 0; i < MyList.getSize(); i++) // for (int 1 = 0; i < LEVELSIZE; i++)
{
AVLNode* n = MyList.remove(i);
out << "level " << i << " " << n->item << "(" << n->height << ") ";
if (n->left != NULL) {
MyList.insert(MyList.getSize(), n->left);
}
if (n->right != NULL) {
MyList.insert(MyList.getSize(), n->right);
}
}
}
out << "\n ";
}
}
void balance (AVLNode *n)
{
if (getHeight(n->left) - getHeight(n->right))
{
balanceToRight(n);
}
if (getHeight(n->right) - getHeight(n->left))
{
balanceToLeft(n);
}
}
int getHeight(AVLNode *& n)
{
if (n == NULL)
{
return 0;
}
else
{
return n->height;
}
}
void balanceToRight(AVLNode * n)
{
if (getHeight(n->left->right) > getHeight(n->left->left))
{
rotateLeft(n->left);
}
rotateRight(n);
}
void rotateRight(AVLNode *&n)
{
AVLNode * k = n->left;
n->left = k->right;
k->right = n;
n = k;
// update heights of k and n
}
void rotateLeft(AVLNode *& n)
{
AVLNode * k = n->right;
n->right = k->left;
k->left = n;
n = k;
// update heights of k and n
}
void balanceToLeft(AVLNode * n)
{
if (getHeight(n->right->left) > getHeight(n->right->right)) // check with TAs if this is right
{
rotateRight(n);
}
rotateLeft(n);
}
/*void updateHeight(AVLNode *& n)
{
}*/
};
Now this is my LinkedList.h
#pragma once
#include <iostream>
#include <cstddef>
#include <fstream>
using namespace std;
template <typename ItemType>
class LinkedList {
struct Node {
ItemType item;
Node *next;
Node *prev;
Node(const ItemType &_item, Node *_next = NULL, Node *_prev = NULL) :
item(_item), next(_next), prev(_prev) { }
};
Node *head;
Node *tail;
int size = 0;
public:
~LinkedList()
{
clear();
}
void insert(int index, ItemType& item) {
if (index > size || size < 0)
{
return;
}
Node * newNode = new Node(item);
if (size == 0)
{
head = newNode;
tail = newNode;
newNode->next = NULL;
newNode->prev = NULL;
size++;
}
else if (index == 0)
{
head->prev = newNode;
newNode->next = head;
head = newNode;
size++;
}
else if (index == size) //INSERTING AT THE END
{
newNode->prev = tail;
newNode->next = NULL;
tail->next = newNode;
tail = newNode;
size++;
}
else {
Node* n = find_node(index);
newNode->next = n;
newNode->prev = n->prev;
n->prev->next = newNode;
n->prev = newNode;
size++;
}
}
Node * remove(int index) {
if (head == NULL || index >= size || index < 0)
{
return NULL;
}
else {
Node* name = find_node(index);
Node * n;
if (size == 1) // REMOVE THE ONLY NODE
{
n = head;
head = NULL;
tail = NULL;
size--;
}
else if (index == 0) //REMOVE THE FIRST NODE WHEN THERE'S MORE THAN ONE IN THE LIST
{
n = head;
head = head->next;
head->prev = NULL;
size--;
}
else if (index == size-1) //REMOVE THE LAST WHEN THERE'S MORE THAN ONE NODE IN THE LIST
{
n = tail;
tail = n->prev;
tail->next = NULL;
size--;
}
else
{
n = find_node(index);
n->prev->next = n->next;
n->next->prev = n->prev;
size--;
}
delete n;
return name;
}
}
Node * find_node(int index)
{
Node * n = NULL;
if (0 <= index && index <= size/2)
{
n = head;
for (int i = 0; i < index; i++)
{
n = n->next;
}
}
else if (size/2 < index && index <= size-1)
{
n = tail;
for (unsigned i = size-1; i > index; i--)
{
n = n->prev;
}
}
return n;
}
int getSize()
{
return size;
}
/* void print(LinkedList <string>& list, ofstream& out, int i)
{
if(head == NULL)
{
return;
}
out << "node " << i << ": " << getItem(i) << "\n";
}
Node* getItem(const int index)
{
if (index > size)
{
return NULL;
}
Node* temp = head;
for (unsigned i = 0; i < size; i++)
{
if (i == index)
{
return temp;
}
temp = temp-> next;
}
return NULL;
}*/
/* int find(const ItemType& item) {
Node * NodeP = head;
for (unsigned i = 0; i < size; i++)
{
if (NodeP->item == item)
{
return i;
}
NodeP = NodeP->next;
}
return -1;
}*/
void clear()
{
while (size != 0){
remove(0);
}
}
};
Thanks so much!
LinkedList::remove returns a LinkedList::Node pointer. You are trying to assign that into an AVLTreeSet::AVLNode pointer.
The AVLTreeSet::AVLNode * you are looking for is in the item member of the returned Node pointer.
You could do something like:
LinkedList<AVLNode *>::Node* n = MyList.remove(i);
AVLNode *treeNode = n->item;
Notes
You should be checking for NULL as the return value for remove, if it doesn't find anything.
remove actually deletes the node then returns it. You are then accessing something that has been deleted, which is Undefined Behavior. You really need to fix this before you go much further.
your for loop will only remove about half of the objects, as your are removing items from the list while still iterating further along the list using i.