forked from cowster36/mazegame
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathavl.h
More file actions
113 lines (96 loc) · 2.61 KB
/
avl.h
File metadata and controls
113 lines (96 loc) · 2.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#pragma once
#ifndef AVL_H
#define AVL_H
#include <iostream>
using namespace std;
struct Node {
string object; int quantity;
Node* left = nullptr, * right = nullptr;
};
string displayInOrder(Node* ptr) {
string str = "";
if (ptr) {
str += displayInOrder(ptr->left);
str += ptr->object + ": " + to_string(ptr->quantity) + " ";
str += displayInOrder(ptr->right);
}
return str;
}
int find(Node* ptr, string str) {
if (ptr) {
if (ptr->object == str) return ptr->quantity;
else {
int l = find(ptr->left, str);
int r = find(ptr->right, str);
return l ? l : r;
}
}
else return 0;
}
int height(Node* n) {
if (!n) return -1;
return max(height(n->left), height(n->right)) + 1;
}
int getbalance(Node* n) {
if (!n) return -1;
return (height(n->left) - height(n->right));
}
Node* rightRotate(Node* node) {
Node* temp1 = node->left;
Node* temp2 = temp1->right;
// Perform rotation
temp1->right = node;
node->left = temp2;
return temp1;
}
Node* leftRotate(Node* node) {
Node* temp1 = node->right;
Node* temp2 = temp1->left;
// Perform rotation
temp1->left = node;
node->right = temp2;
return temp1;
}
Node* insertNode(Node* n, string obj, int num) {
if (!n) return new Node{ obj, num };
else if (n->quantity > num) n->left = insertNode(n->left, obj, num);
else if (n->quantity < num) n->right = insertNode(n->right, obj, num);
else return n;
int balance = getbalance(n);
if (balance > 1 && num < n->left->quantity) return rightRotate(n);
if (balance < -1 && num > n->right->quantity) return leftRotate(n);
if (balance > 1 && num > n->left->quantity) {
n->left = leftRotate(n->left);
return rightRotate(n);
}
if (balance < -1 && num < n->right->quantity) {
n->right = rightRotate(n->right);
return leftRotate(n);
}
return n;
}
void change(Node* ptr, string s, int i) {
if (ptr) {
change(ptr->left, s, i);
if (ptr->object == s) ptr->quantity = i;
change(ptr->right, s, i);
}
}
class Inventory {
Node* root;
public:
Inventory() : root(nullptr) {}
void set(string str, int i) {
change(root, str, i);
}
int get(string key) {
return find(root, key);
}
string display() {
return displayInOrder(root) + "\n";
}
void insert(string obj, int num) {
root = insertNode(root, obj, num);
}
};
#endif